var childPageObj = null;//菜鸟打印面单+拣货单时，打开的子页面对象数据
/** 刷新局部页面 **/
var refreshAjaxPage = function (status) {
	$('#dxmPackageDetailDiv').empty();
    var $keepState = $('#keepState'),
		behindState = $keepState.attr('data-behindState');
    if(behindState == 1){
        orderBehind.pageList();
        return;
    }
	if(status === 'package') {
		$('#contentTabNum').val('3');
	} else if (status === 'closeTip' && +isWait) {//如果是更换运单号，并且申请过运单号，关闭弹层时加个弹层提示
		var closeApplyTipBtn = $('.closeApplyTipBtn'), //弹层的关闭按钮
			countNum = 5, //倒计时
			clearSetInter = null;

		closeApplyTipBtn.addClass('no-drop').find('#closeTimeText').text('(5s)'); //先把关闭按钮禁用
		$('#closeApplyTrackShowTipModal').modal('show');
		clearSetInter = setInterval(function () { //加个定时器
			countNum--;
			$('#closeTimeText').text('(' + countNum + 's)');
			if (!+countNum){ //当倒计时5秒后，关闭按钮解除禁用
				clearInterval(clearSetInter);
				clearSetInter = null;
				closeApplyTipBtn.removeClass('no-drop').find('#closeTimeText').text('');
			}
		}, 1000);
		return;
	}
	//延迟关闭，在不弹出提示弹层的时候才正常关闭
	$('#executeChangePackageNumModel').modal('hide');
	//关闭详情弹层时,把值初始化,下次点击详情时默认选中物流信息
	$('#batchOperatorBtn1').removeAttr('onclick');
	$('#batchOperatorBtn2').removeAttr('onclick');
	typeof operationClear === 'function' && operationClear($('#clearPrintAllBtn'));

	var url = $keepState.data('ajaxurl'),
		ajaxPostData = $keepState.data('ajaxpostdata'),
    	state = $keepState.data('state'),
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (!url) {
		//以下判断条件不要改成===，否则会有问题，参数会不对导致页面查询出来的数据不对
		var isVoided = $keepState.data('isvoided');
		if (isVoided == undefined || isVoided == '') {
			isVoided = '0';
		}
		var isRemoved = $keepState.data('isremoved');
        if (isRemoved == undefined) {
            isRemoved = 0;
		}
		var isSearch = $keepState.data('search');
		if (isSearch == undefined || isSearch == '') {
			isSearch = '0';
		}
		var startTime = $keepState.data('starttime');
		if (startTime == undefined) {
			startTime = '';
		}
		var endTime = $keepState.data('endtime');
		if (endTime == undefined) {
			endTime = '';
		}
		var orderField = $keepState.data('orderfiled');
		if (orderField == undefined) {
			orderField = 'order_pay_time';
		}
		var shopId = $keepState.data('shopid');
		if (shopId == undefined || shopId == '') {
			shopId = -1;
		}
		var storageId = $keepState.data('storageid');
		if (storageId == undefined || storageId == '') {
			storageId = 0;
		}
		var isOversea = $keepState.data('isoversea');
		if (isOversea == undefined || isOversea == '') {
			isOversea = 0;
		}
		var history = $keepState.data('history');
		if(!history) {
			history = '';
		}
		url = 'package/list.htm?pageNo=1&shopId=' + shopId + '&state=' + state
			+ '&isVoided=' + isVoided + '&isRemoved=' + isRemoved + '&isSearch=' + isSearch
			+ '&orderField=' + orderField + '&startTime=' + startTime + '&endTime=' + endTime
			+ '&storageId=' + storageId + '&isOversea=' + isOversea + '&history=' + history;
	}
	if (ajaxPostData && shopGroupId) ajaxPostData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	MYJ.ajax({
		type: !ajaxPostData ? 'GET' : 'POST',
		url: url,
		data: !ajaxPostData ? {} : ajaxPostData,
		success: function (data) {
			
			//后期替换成服务器返回界面
			 //测试数据
			$('#dxmBody').html(data);
			$('#selectedData').empty();
			refreshCountNum();
			var checkName = 'packageId',
				splited = $('#splited').val();
			if(state === 'approved' && splited === 'splited'){
                checkName = 'mergedName';
			}
            refreshOrderProfit(0,checkName);
		}
	});
	$keepState.data({'currOrderNum': -1, 'lookOccupyNum': -1});
	refreshStateCount();
};

//强制关闭申请运单号模态层
var closeApplyTrackTipModal = function (obj) {
	if (!$(obj).hasClass('no-drop')) {
		$('#closeApplyTrackShowTipModal').modal('hide');
		refreshAjaxPage();
	}
};

//关闭库存占用详情弹层
var closeOccupyStockDetailModal = function (modalName) {
	var $modal = $('#lookOccupyStockModal'),
		isNoRefreshPageList = +($modal.attr('data-type')) === 1;//是否不需要刷新列表页

	$modal.modal('hide');
	if (!isNoRefreshPageList) refreshAjaxPage('package');
};

// 将当前选项的URL保存为全部变量，用于刷新页面
function keepUrl(url, isQuery) {
	$("#keepState").data("url", url);				// 访问的URL
	$("#keepState").data("isQuery", isQuery);		// 是否是查询
}

// 选择所有页---------用了
function selAllPage(obj, name) {
	var isChecked = $(obj).is(':checked');
	if (isChecked) {
		$("input[name='curPage']").prop("checked", true);
		$("input[name='" + name + "']").prop("checked", true);
	} else {
		$("input[name='curPage']").prop("checked", false);
		$("input[name='" + name + "']").prop("checked", false);
	}
}

// 日期
var dateStr = function (n) {
	var myDate = new Date(new Date() - 1000 * 60 * 60 * 24 * n);
	var yyyy = myDate.getFullYear();    //获取完整的年份(4位,1970-????)
	var MM = myDate.getMonth() + 1;       //获取当前月份(0-11,0代表1月)
	var dd = myDate.getDate();
	if (MM < 10) {
		MM = "0" + MM;
	}
	if (dd < 10) {
		dd = "0" + dd;
	}
	var dateStr = yyyy + "-" + MM + "-" + dd;
	return dateStr;
};

/** 批量修改物流方式，显示物流选择框 **/
var shippedShowBatchProvider = function(val){
	var isAll = $('#allPage').is(':checked'),
		packageIds = ''; // 如果没有选中所有页，要判断用户是否已选择订单
	if(!isAll){
		packageIds = getCheckBoxValByName('packageId');
		if(!packageIds){
			$.fn.message({type:'error',msg:'请至少选择一个订单'});
			return;
		}
	}
	var $shippedBatchProviderSelect = $('#shippedBatchProviderSelect');
    if(!$shippedBatchProviderSelect.find('option').length){
        getAuthList('shippedBatchProviderSelect');
    }else{
        $shippedBatchProviderSelect.val('').trigger('chosen:updated');
	}
	$('#orderTypeHidden').val(val);
	$('#shippedBatchUpdateProvider').modal('show');
};
var shippedBatchUpdateProvider = function () {
	// 所有页是否被选中
	var isAll = $("#allPage").is(':checked');
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = "";
	if(!isAll){
		packageIds = getCheckBoxValByName("packageId");
		if(packageIds == ""){
			$.fn.message({type:"error",msg:"请至少选择一个订单"});
			return;
		}
		isAll = 0;
	}else{
		isAll = 1;
	}
	var authId = $("#shippedBatchProviderSelect").val();
	if(authId == '' || authId == 0){
		$.fn.message({type:"error",msg:"请选择物流方式"});
		return;
	}
	var orderType = $("#orderTypeHidden").val();
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/shippedBatchUpdateProvider.json',
		data: {
			"packageIds":packageIds,
			"isAll":isAll,
			"authId":authId,
			"orderType":orderType
		},
		dataType: "json",
		success: function(data){
			if(data.code == 0){
				var successList = data.bor.successList;
				var failList 	= data.bor.failList;
				$("#resultFailDetail").empty();
				$("#resultFailNum").html("0 个");
				$('#loading').modal('hide');
				var successNum = successList.length;		// 成功数量
				var failNum = failList.length;			// 失败数量
				if (successNum > 0 && failNum == 0) {
					// 全部成功，只显示提示框信息
					$("#resultSuccessDetail").html("成功："+successNum+" 个包裹已放入到「更换物流管理」");
				} else {
					// 一部分成功，一部分失败
					var failDetail = "<table class='errorMsgTab'><tr><td style='width: 65px;'><span>失败详情：</span></td><td class='fRed'>";
					if (failList.length > 0) {
						for (var i = 0; i < failList.length; i++) {
							var obj = failList[i];
							if (obj.id == null || obj.id == "") {
								failDetail = failDetail + "<p style='margin-bottom:10px;'>" + obj.msg + "</p>";
							} else {
								failDetail = failDetail + "<p style='margin-bottom:10px;'>包裹号：「" + obj.id + "」" + obj.msg + "</p>";
							}
						}
					}
					failDetail += '</td></tr></table>';
					$("#resultSuccessDetail").html("成功："+successNum+" 个包裹已放入到「更换物流管理」");
					$("#resultFailNum").html(failNum+" 个");
					failDetail = strFilterUrl(failDetail);
					$("#resultFailDetail").html(failDetail);
					if (successNum > 0) {
						$("#successDl").css("display", "");
					} else {
						$("#successDl").css("display", "none");
					}
				}
				$("#shippedBatchUpdateProvider").modal("hide");
				$("#batchChangeAgentBtn").attr("onclick", "window.open('orderShipped/index.htm?orderType="+ orderType +"')");
				$("#batchChangeAgentRetModal").modal("show");
			}else{
				$.fn.message({type:"error", msg:data.msg});
				$('#loading').modal('hide');
			}
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/* 特殊货代物流已发货批量换物流 */
var shippedBatchUpdateForSpecialProvider = function () {
	// 所有页是否被选中
	var isAll = $("#allPage").is(':checked');
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = "";
	if(!isAll){
		packageIds = getCheckBoxValByName("packageId");
		if(packageIds == ""){
			$.fn.message({type:"error",msg:"请至少选择一个订单"});
			return;
		}
		isAll = 0;
	}else{
		isAll = 1;
	}
	var authId = $("#shippedBatchProviderSelect").val();
	if(authId == '' || authId == 0){
		$.fn.message({type:"error",msg:"请选择物流方式"});
		return;
	}
	$('#loading').modal('show');
	$("#zwsdIsAll").val(isAll);
	$("#zwsdPackageIds").val(packageIds);
	$.ajax({
		type: "POST",
		url: 'order/shippedBatchUpdateForSpecialProvider.json',
		data: $("#zwsdWklForm").serialize(),
		dataType: "json",
		success: function(data){
			if(data.code == 0){
				var successList = data.bor.successList;
				var failList 	= data.bor.failList;
				$('#loading').modal('hide');
				var successNum = successList.length;		// 成功数量
				var failNum = failList.length;			// 失败数量
				if (successNum > 0 && failNum == 0) {
					// 全部成功，只显示提示框信息
					$("#resultSuccessDetail").html("成功："+successNum+" 个包裹已放入到「更换物流管理」");
				} else {
					// 一部分成功，一部分失败
					var failDetail = "<table class='errorMsgTab'><tr><td style='width: 65px;'><span>失败详情：</span></td><td class='fRed'>";
					if (failList.length > 0) {
						for (var i = 0; i < failList.length; i++) {
							var obj = failList[i];
							if (obj.id == null || obj.id == "") {
								failDetail = failDetail + "<p style='margin-bottom:10px;'>" + obj.msg + "</p>";
							} else {
								failDetail = failDetail + "<p style='margin-bottom:10px;'>包裹号：「" + obj.id + "」" + obj.msg + "</p>";
							}
						}
					}
					failDetail += '</td></tr></table>';
					$("#resultSuccessDetail").html("成功："+successNum+" 个包裹已放入到「更换物流管理」");
					$("#resultFailNum").html(failNum+" 个");
					failDetail = strFilterUrl(failDetail);
					$("#resultFailDetail").html(failDetail);
					if (successNum > 0) {
						$("#successDl").css("display", "");
					} else {
						$("#successDl").css("display", "none");
					}
				}
				$("#shippedBatchUpdateProvider").modal("hide");
				$("#zwsdWklShip").modal("hide");
				var orderType = $("#zwsdOrderType").val();
				$("#batchChangeAgentBtn").attr("onclick", "window.open('orderShipped/index.htm?orderType="+ orderType +"')");
				$("#batchChangeAgentRetModal").modal("show");
			}else{
				$.fn.message({type:"error", msg:data.msg});
			}
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 同步订单 **/
function syncFromWish() {

	var status = "进行中...";

	var progressBar = $("#progressBar");
	// 先隐藏起来(防止出现进度条后退的效果)
	progressBar.css("width", "0%");
	progressBar.css("display", "");
	$("#syncFromWishModal_status").html(status);
	$("#syncFromWishModal_processDetail").empty();

	$("#syncFromWishModal").modal("show");
	var p = 0;		// 记录进度条的值
	$.ajax({
		type: "POST",
		url: "order/syncOrderFromWish.json",
		data: {},
		dataType: "json",
		success: function (data) {
			var uuid = data.uuid;

			checkProcessStatus(uuid, function (data) {
				var num = data.num;
				if (data.num > 100) {
					num = data.num % 100;
				}

				if (num < p && data.code != 1) {
					// 为了去掉变为n->0时的动画效果，在此先隐藏，然后再置0，最后再定时显示出来
					progressBar.css("display", "none");
					setTimeout(function () {
						progressBar.css("display", "");
					}, 1000);
				}

				p = num;

				if (data.code == 0) {
					$("#progressBar").css("width", num + "%");
				} else {
					status = "已完成!";
					$("#progressBar").css("width", "100%");
					$("#progressBar").removeClass("active");
				}
				$("#syncFromWishModal_status").html(status);
				$("#syncFromWishModal_processDetail").html(data.msg);
			});
		}
	});
}

/** 关闭同步 **/
var closeSync = function () {
	var locHref = gitWinLocHref();
	window.location.href = locHref + "order/index.htm";
};

/** 验证物流追踪号 **/
var validateTrackNum = function (trackNum) {
	var validateTrackNum = /^[a-zA-Z0-9]{6,30}$/;
	if (trackNum == '') {
		$.fn.message({type: "error", msg: "物流追踪号不能为空!"});
		return true;
	}
	if (!trackNum.match(validateTrackNum)) {
		$.fn.message({type: "error", msg: "物流追踪号格式不正确!格式：6-30个字符,包含字母数字"});
		return true;
	}
	return false;
};

/** 切换状态选择 **/
var selStateCondition = function(state, isSearch, orderField, begin, end, isVoided, isOversea, history, isTimeout){
    var $keepState = $('#keepState'),
        obj = {
            'state': state,
			'shopid': -1,
            'searchtype': 'orderId',
            'authid': '-1',
            'country': '',
            'platform': '',
            'search': isSearch,
            'orderfiled': orderField,
            'starttime': begin,
            'endtime': end,
            'shippedtype': -1,
            'isvoided': isVoided,
            'ruleid': '-1',
            'isoversea': isOversea,
            'sysrule': '',
            'applytype': '',
            'printjh': '-1',
            'printmd': '-1',
            'productstatus': '',
            'jhcomment': '-1',
            'storageid': '0',
            'custom': '-1',
            'history': history,
            'selecttype': 1,
            'forbiddenreason': '0'
        };

    $('#merged').val('');
    $('#splited').val('');
	obj['isremoved'] = (state == '' && isVoided < 1) ? '-1' : '0';
	if(state == '' || state === 'shipped' || state === 'refound' ){
        obj['isfree'] = '-1';
        obj['isbatch'] = '-1';
	} else {
        obj['isfree'] = '0';
        obj['isbatch'] = '0';
	}
	/** 新版本 **/
	var newVersion = $('#newVersion').val();
    obj['forbiddenstatus'] = (+newVersion === 1 && state === 'allocated_has') ? '0' : '-1';

	$keepState.data(obj);
	$('input[name="productStatus"]').prop('checked', false);
	$('input[name="jhComment"]').prop('checked', false);
	toSwitchState(isTimeout);	// 搜索订单
};

// 选择订单的某个状态
var selState = function (id, state, isVoided, isSearch, history, isTimeout) {
	var $keepState = $('#keepState');
	$keepState.data({
		'orderFlipType': 'package',
		'applystatus': ''
	});
	if(state != '' || isVoided == 1){
		$('#timeOutHidden').val('0');
		$('#buyerAccountHidden').val('');
		$('#orderIdHidden').val('');
    }

	var obj = {
        'paid': '#paidNum', // 待审核
        'approved': '#approvedNum', // 待处理
        'processed': '#processHomeNum', // 运单号
        'allocated_has': '#allocatedHasNum', // 有货
        'allocated_out': '#allocatedOutNum', // 缺货
        'allocated_exception': '#allocatedExceptionNum', // 待打单（异常）
        'shipped': '#shippedNum', // 发货
        'refound': '#refoundNum', // 已退款
        'abnormal': '#voidedNum' // 已搁置
	};
	//如果state有值，则取对应状态的节点的text赋值，如果state没值则是全部订单，直接赋值0
	if (state) {
		if (obj[state]) { //判断obj对象中是否有对应状态字段，有才赋值
			$('#totalNum').val($(obj[state]).text());
		}
	} else { //全部订单
		$('#totalNum').val('0');
	}
	if(state === 'processed'){ // 运单号
		$keepState.data('applystatus', 'success');
	}
	isVoided = isVoided || 0;
	isSearch = isSearch || 0;
	if (state == undefined) {
		state = '';
	}
	if(!history){
		history = '';
	}else{
		$('#liOne').find('.treeBackgrounda').removeClass('treeBackgrounda');
		$('#' + id).parent().addClass('treeBackgrounda');
	}
	var begin = '',
		end = '',
		orderField = 'order_pay_time';
	if (state === 'shipped') {
		var commitPlatform = $keepState.data('commitplatform');
		if (commitPlatform === 'success') {
			begin = dateStr(59);
			end = dateStr(0);
			orderField = 'shipped_time';
		}
	} else if (state == '') {
		orderField = 'order_create_time';
		$keepState.data('commitplatform', '');
	}else if (state === 'refound') {
        orderField = 'refunded_time';
        isSearch = 1;
		$keepState.data({
			'commitplatform': '',
			'refundstatus': '0'
		});
    } else {
		$keepState.data('commitplatform', '');
	}
	if(isTimeout === 'timeout'){ //如果是首页点击剩余发货跳到订单页面的
        isSearch = 0;
        orderField = 'order_timeout_time';
	}
	selStateCondition(state, isSearch, orderField, begin, end, isVoided, -1, history, isTimeout);
};

/*订单搁置页checkbox仅显示移除订单*/
var onlyShowRemoveOrder = function (obj) {
	var checked = $(obj).is(':checked');

	$('.invoideOrderBatchOp').not('.selCustomTagsDiv')[checked ? 'hide' : 'show']();// 选中"仅显示不再关注记录"隐藏其他相关批量操作,取消选中则还原显示回批量操作按钮
	$('.selCustomTagsDiv').each(function () {//处理除批量标记外的其他按钮的显示与隐藏
		//“仅显示不再关注记录”按钮取消或勾选时，批量打单标记和批量还原操作不隐藏
		$(this).find('ul.selCustomTagsMenu > li').not('.selCustomTagsLi,.batchRestoreLi')[checked ? 'hide' : 'show']();
	});
	$('#keepState').data('isremoved', checked ? '1' : '0');

	//不再关注按钮显示隐藏
	hasPutHoldMethod();

	packageList();
};

/** 已搁置按钮显示判断 **/
var hasPutHoldMethod = function () {
	var checked = $('#onlyShowRemove[name="onlyShowRemove"]').is(':checked'),
		$dailySaleSetD = $('#dailySaleSetID'),
		$batchRestoreLi = $('.batchRestoreLi'),
		dailySale = $dailySaleSetD.attr('data-sale'),
		dailySet = $dailySaleSetD.attr('data-set');

	if(+dailySale === 1 && +dailySet === 1 && checked){
		$batchRestoreLi.addClass('hide');
	}else{
		$batchRestoreLi[checked ? 'removeClass' : 'addClass']('hide');
	}
}

/** 设置海外仓 **/
var setOverseaWarehose = function(id, state, isOversea){
	if(isOversea == 0){
		$("#liOne").find(".treeBackgrounda").removeClass("treeBackgrounda");
		$("#" + id).parent().addClass("treeBackgrounda");
	}
	$("#keepState").data("isoversea", isOversea);
	$("#keepState").data("applystatus", isOversea !=2 ? "success" : "commit_success");
	$("#keepState").data("commitplatform", "");
	$("#timeOutHidden").val("0");
	$("#buyerAccountHidden").val("");
	selStateCondition(state, 0, "order_pay_time", "", "", 0, isOversea, "");
};

//切换店铺
var selShop = function (shopId, obj) {
	var $keepState = $('#keepState');
	$keepState.data('shopid', shopId);
	if($keepState.data('state') === 'approved'){
		showHideBtn();
	}
	setClass(obj);
	packageList();
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
};

var showHideBtn = function(){
	$('#merged').val('');
	$('#splited').val('');
	$('#batchMergeBtn').css('display', 'none');
	$('#batchMergeBtn1').css('display', 'none');
	$('#batchBtnDiv').css('display', '');
	$('#batchBtnDiv1').css('display', '');
	$('#moveProcessBtn').css('display', '');
	$('#moveProcessBtn1').css('display', '');
};

/** 设置平台的店铺显示 **/
var setPlatformShop = function (platform, op) {
	var $shopDiv = $('#shopDiv'),
		$singleShopDiv = $shopDiv.find('.singleShopDiv'),
		$shopA = $singleShopDiv.length ? $singleShopDiv.find('a') : $shopDiv.find('a');//兼容使用了多店铺分组的节点

	$shopA.each(function () {
		var val = $(this).attr("data-platform");
		if (val == platform || val == "" || platform == "") {
			$(this).css("display", "");
		} else {
			$(this).css("display", "none");
		}
	});
	if ($singleShopDiv.length && $singleShopDiv.is(':hidden') && op && !op.shopGroupId) {//店铺账号如果展示的是多店铺分组，则切换平台渠道的时候默认选中全部
		typeof SHOP_GROUP !== 'undefined' && typeof SHOP_GROUP.getShopGroupList === 'function' && SHOP_GROUP.getShopGroupList({type: 'update', state: 'noAjax', call: op.call ? op.call : null});//更新生成新的分组节点
	} else {
		if (typeof SHOP_GROUP !== 'undefined' && (typeof SHOP_GROUP.initShopIsShowHide === 'function')) {
			SHOP_GROUP.initShopIsShowHide('update');
		} else if (typeof initShopIsShowHide === 'function') {
			initShopIsShowHide();
		}
		op && op.call && typeof op.call === 'function' && op.call()
	}
};

/** 设置平台 **/
var selPlatform = function (platform, obj) {
    var $keepState = $('#keepState'),
		$shopGroupId = $('#shopGroupId'),
        $productIdA = $('.productIDA'),
        currentType = $('.orderSearchType .myj-active').data('name'),
        curAdvSearchType = $('#advSearchType').val(),
		isShopGroupState = $shopGroupId.length > 0;//是否有多店铺分组
	// 更新搜索类型，如果当前是产品ID需要切换到第一个类型
    $productIdA.addClass("hide");
    if (platform === 'smt' || platform === 'shopee' || platform === 'ebay') {
        $productIdA.removeClass("hide");
    } else if(currentType === 'productId' || curAdvSearchType === 'productId'){
		var $firstSearchType = $('.orderSearchType a').first();
		setSearchType($firstSearchType.data('name'), $firstSearchType);

        $("#advSearchType").find("option").first().prop('selected', true);
        setAdvSearchType(0, $('#advSearchType'));
    }

    $keepState.data('platform', platform);
    $keepState.data('shopid', -1);
	setClass($('#shopAllDiv'));
	setClass(obj);
    if($keepState.data('state') === 'approved'){
        showHideBtn();
    }
    if (isShopGroupState) {//如果加了多店铺分组，则走这里的逻辑，如果不是则走原流程
		setPlatformShop(platform, {shopGroupId: '', call: packageList});
	} else {
		setPlatformShop(platform);
		packageList();
	}
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式

	//显示 批量删除手工单按钮 （ 订单状态===待审核/待处理 && 平台渠道===其他）
	var curState = $keepState.data('state'),
		curPlatform = $keepState.data('platform');
	if ((curState === 'paid' || curState === 'approved') && curPlatform === 'our') {
		$('.batchDelectBtn').removeClass('hide');
	} else {
		$('.batchDelectBtn').addClass('hide');
	}
};

/** 设置当前选中效果 **/
var setClass = function (obj) {
	$(obj).parent().find(".myj-active").removeClass("myj-active");
	$(obj).addClass("myj-active");
};
/** 设置待打单选中 **/
var selAllocated = function (id, state, isVoided, isSearch) {
	$("#liOne").find(".treeBackgrounda").removeClass("treeBackgrounda");
	$("#" + id).parent().addClass("treeBackgrounda");
	selState(id, state, isVoided, isSearch);
};

/** 设置已发货 **/
var setShipped = function(id, state, commit){
	$("#keepState").data('commitplatform', commit);
	var isSearch = 0;
	if(state == 'shipped' ){
		if (commit == 'success') {
            isSearch = 1;
        } else if (commit = 'fail') {
            $("#keepState").data('behindtrack', 0);
		}
	}
	selAllocated(id, state, 0, isSearch);
};

/** 设置搜索类型 **/
var setSearchType = function (type, obj) {
	var $searchContent = $('#searchContent'),
		isReplaceEmoji = false;
	$('#keepState').data('searchtype', type);
	document.onmouseup = function (e) {
		if($(e.target).hasClass('textareaSearch') || $(e.target).closest('.btnsss').length || $(e.target).hasClass('openSearchIcon')) return;
		MULTI_SEARCH.closeText();
		if(type === 'fCode'){
			$('.batchSearchType').addClass('p-left30');
			$('.openSearchIcon').removeClass('hide');
		}
	};
	setClass(obj);
	MULTI_SEARCH.closeText(); //关闭已打开的多个搜索 textarea
	if(type === 'orderId' || type === 'packageNumber' || type === 'trackNumber' || type === 'sku'){
		/*$('.openSearchIcon').css({
			'top': '12px',
			'left': '6px'
		})*/
	}else if(type === 'fCode'){
		$('.batchSearchType').addClass('p-left30');
		$('.openSearchIcon').removeClass('hide');
	}else if(type === 'skuCode' || type === 'productSku' || type === 'productId' || type === 'email'){
		$('.batchSearchType').removeClass('p-left30');
		$('.openSearchIcon').addClass('hide');
	}
	//商品sku、平台编号不显示模糊搜索功能
	var $orderSearchType = $('select#orderSearchType'),
		maxNumText,
		isExtendedOrderId = type === 'extendedOrderId',
		isProductId = type === 'productId',
		isEmail = type === 'email',
		isProductSku = type === 'productSku';

	$orderSearchType[(isProductSku || isExtendedOrderId || isProductId || isEmail) ? 'addClass' : 'removeClass']('hide');
	if (isProductSku || isExtendedOrderId || isProductId || isEmail) $orderSearchType.val('1');//只选择精确搜索

	switch (+$orderSearchType.val()) {
		case 0:
			maxNumText = 30; // 模糊匹配
			break;
		case 1:
			maxNumText = 1000; // 精确匹配
			break;
		case 2:
			maxNumText = 200; // 完全匹配
			break;
	}
	$searchContent.attr({
		'data-maxnum': maxNumText, // 最大数量限制
		'data-spacewrap': true // 是否支持空格分隔
	});
	MULTI_SEARCH.setSpaceWrap(true); // 支持空格隔开
	if(type === 'orderId') {
		$searchContent.attr('placeholder', '多个订单号间用逗号或空格隔开,最多支持' + maxNumText + '个');
		isReplaceEmoji = true;
	} else if(type === 'packageNumber') {
		$searchContent.attr('placeholder', '多个包裹号间用逗号或空格隔开,最多支持' + maxNumText + '个');
		isReplaceEmoji = true;
	} else if(type === 'trackNumber') {
		$searchContent.attr('placeholder', '多个跟踪号间用逗号或空格隔开,最多支持' + maxNumText + '个');
		isReplaceEmoji = true;
	} else if(type === 'sku') {
		$searchContent.attr({
			'placeholder': '多个平台SKU间用逗号隔开,最多支持' + maxNumText + '个',
			'data-spacewrap': ''
		});
		MULTI_SEARCH.setSpaceWrap(false); // 不支持空格隔开
	} else if(type === 'fCode') {
		$searchContent.attr('placeholder', '多个物流商单号间用逗号或空格隔开,最多支持' + maxNumText + '个');
		isReplaceEmoji = true;
	} else if(type === 'extendedOrderId') {
		$searchContent.attr('placeholder', '多个平台编号间用逗号或空格隔开,最多支持' + maxNumText + '个');
		isReplaceEmoji = true;
	} else if(type === 'sellerComment') {
		$searchContent.attr({
			'data-maxnum': '',
			'data-spacewrap': '',
			'placeholder': '请输入至少两个非空字符'
		});
	} else{
		$searchContent.attr({
			'data-maxnum': '',
			'data-spacewrap': '',
			'placeholder': ''
		});
		document.onmouseup = null;

		if (type === 'productSku' || type === 'productId' || type === 'email'){
			isReplaceEmoji = true;
		}
	}

	$searchContent.off('input.replaceEmoji');
	$(document).off('input.replaceEmoji', '.textareaSearch');
	if (isReplaceEmoji) {
		inputEmptyEmojiCode($searchContent);
		$searchContent.on('input.replaceEmoji', function () {
			inputEmptyEmojiCode(this);
		});

		$(document).on('input.replaceEmoji', '.textareaSearch', function () {
			if ($(this).closest('#searchDiv').length) {
				inputEmptyEmojiCode(this);
			}
		});
	}
};
// 切换匹配类型（搜索/高级搜索）
var changeSearchType = function (obj, isAdvanced) {
	if (isAdvanced) {
		// 高级搜索
		setAdvSearchType(0, obj);
	} else {
		// 搜索
		var $acticeType = $('#searchTypeDiv').find('a.myj-active'),
			type = $acticeType.attr('data-name');
		setSearchType(type, $acticeType);
	}
}

/** 筛选 **/
var setChoose = function (val) {
	$("#searchContent").val("");
	$("#keepState").data("search", "0");
	setClass($("#allAuthId"));
	setClass($("#allState"));
	setClass($("#allSearchType"));
	if (val == 1) {
		searchOrder();
	} else if (val == 2) {
		packageList();
	}
};

/** 设置搜索 **/
var setSearch = function () {
	$("#keepState").data("state", "");
	$("#keepState").data("authid", "-1");
	$("#keepState").data("search", "1");
	$("#keepState").data("country", "");
};

/** 全局搜索 **/
var globalSearch = function (val) {
	$("#keepState").data("state", "");
	$("#keepState").data("stateName", "");
	$("#keepState").data("shopid", -1);
	$("#keepState").data("searchtype", "orderId");
	$("#keepState").data("authid", "-1");
	$("#keepState").data("country", "");
	$("#keepState").data("platform", "");
	$("#keepState").data("search", "0");
	$("#keepState").data("exportstate", "");
	$("#keepState").data("orderfiled", "");
	$("#keepState").data({"ajaxurl": "order/list.htm?pageNo=0&shopId=-1&search=0&state=", "ajaxpostdata": null});

	var url = "order/order.htm?pageNo=0&shopId=-1&search=0&state=";
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: url,
		data: {},
		dataType: "html",
		success: function (data) {
			$('#rightBody').empty();
			$('#rightBody').html(data);
			$('#loading').modal('hide');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 打单类型全部 **/
var clearPrintStatus = function (obj) {
	$("#keepState").data("printjh", "-1");
	$("#keepState").data("printmd", "-1");
	setClass(obj);
	packageList();
};

/** 运单号状态全部 **/
var clearApplyTrackNumStatus = function (obj) {
	$("#keepState").data("applytype", "");
	$("#keepState").data("applystatus", "");
	setClass(obj);
	packageList();
};

var setPackageType = function (obj) {
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	$("#keepState").data("productstatus", "");
	$("#keepState").data("jhcomment", "-1");
	$("input[name='productStatus']").prop("checked", false);
	$("input[name='jhComment']").prop("checked", false);
	setClass(obj);
	packageList();
};

var setProductStatus = function (e) {
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	var $productStatus = $(e).closest('td').find('[name="productStatus"]:checked'),
		productStatus = '';
    $.each($productStatus,function(i,j){
        var v = $(j).val();
        productStatus += (!productStatus ? '' : ',') + $(j).val();
    });
	$('#keepState').data('productstatus', productStatus);
	packageList();
	removeActive(e);
	// 批量打印筛选
	typeof operationClear === 'function' && operationClear($('#clearPrintAllBtn'));
};
var removeActive = function (obj) {
	var div = $(obj).closest('div');
	var length = div.find('input[type=checkbox]:checked').length;
	if (length > 0) {
		div.find('a').removeClass('myj-active');
	} else {
		div.find('a').addClass('myj-active');
	}
};
var setJhComment = function (obj) {
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	var isSelect = $(obj).is(":checked");
	if (isSelect) {
		$("#keepState").data("jhcomment", "1");
	} else {
		$("#keepState").data("jhcomment", "-1");
	}
	packageList();
	removeActive(obj);
};
// 设置点击未提交上网时候设置提交状态为未上网，后置单号状态置为0
var setFailConditon = function (commitState, behindTrack, obj) {
	$('#keepState').data('behindtrack', behindTrack);
	// 补录页面的批量处理错误不显示
	$('#dealError,#dealError1').css('disaply', +behindTrack === 1 ? 'none' : '');
	if(commitState == 'fail'){
		$('#changeAgentLabel').css('display','');
	} else {
		$('#changeAgentLabel').css('display','none');
	}
	setCondition('commitplatform', commitState, obj);
};

/** 设置查询条件 **/
var setCondition = function (key, val, obj) {
	var $keepState = $('#keepState');
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	showHideBtn();
	/*if (key == 'commitplatform' && val == 'fail') {
	 $("#batchIgnoreCommitFailBtn").css("display", "");
	 } else {
	 $("#batchIgnoreCommitFailBtn").css("display", "none");
	 }*/
	$keepState.data(key, val);
	setClass(obj);
	var tipText = '「虚拟发货」把运单号提交给平台，但不真实发走货物';

	if ("shippedtype" == key && val == 0) {
		$keepState.data('starttime', '');
		$keepState.data('endtime', '');
	}
	if ("state" == key && val == 'shipping_fail') {
		$("#batchBackAllocateBtn").css("display", "");
		$("#shippingReShipBtn").css("display", "");
	} else {
		$("#batchBackAllocateBtn").css("display", "none");
		$("#shippingReShipBtn").css("display", "none");
	}
	if ("storageId" === key) {
		refreshCountNum();
	}
	if ("printmd" === key) {
		$keepState.data("printjh", "-1");
	}
	if ("printjh" === key) {
		$keepState.data('printmd', '-1');
	}
	if ("sysrule" === key) {
		$keepState.data('ruleid', '-1');
	}
	if ("ruleid" === key) {
		$keepState.data('sysrule', '');
	}
	if(key === 'authid') {
		var smtBatch= $(obj).attr('data-smt-batch');
		if (smtBatch === 'true') {
			$('.smtInWayBillNo').attr({
				'data-auth-id': val,
				'data-auth-text': $(obj).attr('data-smt-batch-title')
			}).removeClass('hide');
		} else {
			$('.smtInWayBillNo').addClass('hide');
		}
	}
	/** 禁止发货 **/
	if("forbiddenreason" != key){
		$keepState.data('forbiddenreason', '0');
	}
    // 每次点击新的tab页都把值重置1
    $('#pageNo').val(1);
    /** 设置批量操作动作 **/
	if('forbiddenstatus' === key){
		$('li.moveToWavetLi')[val === '0' ? 'addClass' : 'removeClass']('hide');
        if (val == '0') {
            //发货中
			$('.waveMoveToAllocateOutLi').addClass('hide');
			$('.waveBatchSignBanShipLi').removeClass('hide');
        } else if (val == '1') {
            // 禁止发货
			$('.waveMoveToAllocateOutLi').removeClass('hide');
			$('.waveBatchSignBanShipLi').addClass('hide');
        } else if (val == '3') {
            //仓库打回
			$('.waveMoveToAllocateOutLi').removeClass('hide');
			$('.waveBatchSignBanShipLi').addClass('hide');
        }
	}

	// 运单号申请状态
	if("applystatus" == key) {
		$('.applyingBatchComment').addClass('hide');
		if(val == 'success' || val == 'commit_success' || val === 'commit_success_to_lock'){
			$("#batchMoveAllocatedBtn").css("display","");
			$("#batchMoveAllocatedBtn1").css("display","");
			$("#applySuccessDiv").css("display","");
			$("#applySuccessDiv1").css("display","");
			$("#applyFailDiv").css("display","none");
			$("#applyFailDiv11").css("display","none");
			$("#applyFailDiv1").css("display","none");
			$("#applyFailDiv22").css("display","none");
			$("#applyFailDiv2").css("display","none");
			$("#applyFailDiv3").css("display","none");
		} else if(val == 'fail'){ // 申请失败
			$("#batchMoveAllocatedBtn").css("display","none");
			$("#batchMoveAllocatedBtn1").css("display","none");
			$("#applySuccessDiv").css("display","none");
			$("#applySuccessDiv1").css("display","none");
			$("#applyFailDiv").css("display","");
			$("#applyFailDiv11").css("display","");
			$("#applyFailDiv1").css("display","");
			$("#applyFailDiv22").css("display","");
			$("#applyFailDiv2").css("display","");
			$("#applyFailDiv3").css("display","");
		} else if(val == 'applying'){ // 申请中
			$("#batchMoveAllocatedBtn").css("display","none");
			$("#batchMoveAllocatedBtn1").css("display","none");
			$("#applySuccessDiv").css("display","none");
			$("#applySuccessDiv1").css("display","none");
			$("#applyFailDiv").css("display","none");
			$("#applyFailDiv11").css("display","none");
			$("#applyFailDiv1").css("display","none");
			$("#applyFailDiv22").css("display","none");
			$("#applyFailDiv2").css("display","none");
			$("#applyFailDiv3").css("display","none");
			tipText = '[申请中]超过20分钟未获取到单号，将进入到申请失败';
			if ($('#orderIsOverSea').val() !== 'true') {//海外仓库申请中不添加此按钮，因为批量操作中有批量拣货说明
				$('.applyingBatchComment').removeClass('hide');
			}
		} else if(val == 'yccommit'){
			$('#yucangCommitLi').addClass('liFoucs').removeClass('bgColorG');
			$('#yucangCancelLi').addClass('bgColorG').removeClass('liFoucs');
		} else if(val == 'yucancel'){
			$('#yucangCommitLi').addClass('bgColorG').removeClass('liFoucs');
			$('#yucangCancelLi').addClass('liFoucs').removeClass('bgColorG');
		}
	}

	//显示隐藏追加商品
	var $batchChaseProduct = $('.batchChaseProduct');
	if (val === 'commit_success_to_lock' || val === 'commit_success') {
		$batchChaseProduct.removeClass('hide');
	} else {
		$batchChaseProduct.addClass('hide');
	}

	var $applyingTipContent = $('#applyingTipContent');

	if ($applyingTipContent.length) $applyingTipContent.text(tipText);
	// 订单搜索
	packageList();
	// 批量打印筛选
	typeof operationClear === 'function' && operationClear($('#clearPrintAllBtn'));

	//显示 批量删除手工单按钮 （ 订单状态===待审核/待处理 && 平台渠道===其他）
	var curState = $keepState.data('state'),
		curPlatform = $keepState.data('platform');
	if ((curState === 'paid' || curState === 'approved') && curPlatform === 'our') {
		$('.batchDelectBtn').removeClass('hide');
	} else {
		$('.batchDelectBtn').addClass('hide');
	}
	$('.operationClear').click(); // 清空选中1000条
};

/** 设置国家查询条件 **/
var setCountryCond = function(val){
	$("#keepState").data("country", val);
	// 订单搜索
	packageList();
};

/** 设置查询条件 **/
var setCondition1 = function (key, val, obj) {
	$("#keepState").data(key, val);

	$(obj).parent().parent().parent().parent().find(".myj-active").removeClass("myj-active");
	$("#dropdownRuleMenu1").addClass("myj-active");
	$(obj).addClass("myj-active");

	// 订单搜索
	packageList();
};

/** 设置排序方式 **/
var setOrderFiled = function (key, val, obj) {
	var $keepState = $('#keepState'),
		orderField = $keepState.data('orderfiled');

	commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	$keepState.data(key, val);
	setClass(obj);
	if($keepState.data('state') === 'approved'){
		showHideBtn();
	}

	var spanObj = $(obj).find('span'),
		attrClass = $(spanObj).attr('class');
	$('#orderFieldDiv').find('span').removeClass('myjCaretDown').removeClass('myjCaretUp');
	$(spanObj).addClass(attrClass);

	var isTop = $(spanObj).hasClass('myjCaretUp'),
		isDown = $(spanObj).hasClass('myjCaretDown');
	if (val == orderField) {
		if (isTop) {
			$(spanObj).removeClass('myjCaretUp').addClass('myjCaretDown');
			$keepState.data('search', 1);
		} else {
			$(spanObj).removeClass('myjCaretDown').addClass('myjCaretUp');
			$keepState.data('search', 0);
		}
	} else {
		$(spanObj).removeClass('myjCaretDown').addClass('myjCaretUp');
		$keepState.data('search', 0);
	}
	packageList();
};

/** 设置排序方式(用于已退款) **/
var setOrderRefundFiled = function (key, val, obj) {
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	var orderField = $("#keepState").data("orderfiled");
	$("#keepState").data(key, val);
	setClass(obj);

	var spanObj = $(obj).find("span");
	var attrClass = $(spanObj).attr("class");
	$("#refoundOrderFieldDiv").find("span").removeClass("myjCaretDown").removeClass("myjCaretUp");
	$(spanObj).addClass(attrClass);

	var isTop = $(spanObj).hasClass("myjCaretUp");
	var isDown = $(spanObj).hasClass("myjCaretDown");
	if('refund_amount_usd' == val){
		if (isDown) {
			$(spanObj).removeClass("myjCaretDown").addClass("myjCaretUp");
			$("#keepState").data("search", 0);
		} else {
			$(spanObj).removeClass("myjCaretUp").addClass("myjCaretDown");
			$("#keepState").data("search", 1);
		}
	}else{
		if (val == orderField) {
			if (isTop) {
				$(spanObj).removeClass("myjCaretUp").addClass("myjCaretDown");
				$("#keepState").data("search", 1);
			} else {
				$(spanObj).removeClass("myjCaretDown").addClass("myjCaretUp");
				$("#keepState").data("search", 0);
			}
		} else {
			$(spanObj).removeClass("myjCaretDown").addClass("myjCaretUp");
			$("#keepState").data("search", 0);
		}
	}
	packageList();
};

/** 订单列表（用于各个状态切换） **/
var toSwitchState = function (isTimeout) {
	var $keepState = $('#keepState'),
		state = $keepState.data('state'),
		isVoided = $keepState.data('isvoided'),
		isRemoved = $keepState.data('isremoved'),
		isOversea = $keepState.data('isoversea'),
		applyStatus = $keepState.data('applystatus'),
		commitPlatform = $keepState.data('commitplatform'),
    	timeOut = $('#timeOutHidden').val(),
		history = $keepState.data('history'),
		// 取cookies中用于所选择的板块记录
		allocatedHasModuleName = typeof myjStorage !== 'undefined' ?myjStorage.get('allocated_has_moduleName')() : '',
		$isNewVersion = $('#newVersion').val(), //是否波次
		pageSize = ORDER_STORAGE_SET.get('pageSize');

	if (commitPlatform == undefined) {
		commitPlatform = '';
	}
	pageSize = pageSize || 100;
	if(state === 'allocated_has' && allocatedHasModuleName === 'group' && +$isNewVersion === 0){
		debugger;
		MYJ.ajax({
			url: 'package/orderGroup/index.htm',
			data: {},
			success: function (data) {
				$('#rightBody').empty().html(data).css('display', '');
				/*加载导航*/
				groupCommSearchList();
				/*加载数据*/
				groupOrderList(+pageSize);
			}
		});
	}else {
		
		var data = packageIndexData();
		//测试数据
		$('#rightBody').empty().html(data).css('display', '');
		
		/** 加载导航 **/
		commSearchList(isTimeout);
		/** 加载数据 **/
		packageList(+pageSize);
		return;
		MYJ.ajax({
			url: 'package/index.htm',
			data: {
				state: state,
				isVoided: isVoided,
				isRemoved: isRemoved,
				isOversea: isOversea,
				commitPlatform: commitPlatform,
				history: history,
				applyStatus: applyStatus,
				timeOut: timeOut
			},
			success: function (data) {
				$('#rightBody').empty().html(data).css('display', '');
				/** 加载导航 **/
				commSearchList(isTimeout);
				/** 加载数据 **/
				packageList(+pageSize);
			}
		});
	}
};

/** 导航列表加载 **/
var commSearchList = function (isTimeout) {
	var $keepState = $('#keepState'),
		state = $keepState.data('state'),
		isVoided = $keepState.data('isvoided'),
		isOversea = $keepState.data('isoversea'),
		commitPlatform = $keepState.data('commitplatform'),
		isFree = $keepState.data('isfree'),
		isBatch = $keepState.data('isbatch'),
		history = $keepState.data('history'),
		prefixCount = $('#prefixCount').val(),
		newVersion = $('#newVersion').val();

	if (commitPlatform == undefined) {
		commitPlatform = '';
	}
	
	//测试数据
	var data = commSearchListData();
	$('#commSearchDiv').empty();
	$('#commSearchDiv').html(data);
	
	if(isTimeout === 'timeout'){ //如果是首页点击剩余发货跳到订单页面的,排序方式选中剩余发货时间
	    var $searchTab = $('#orderFieldDiv .searchTab');
	    $searchTab.find('.myj-active').removeClass('myj-active').find('span').removeClass('myjCaretDown myjCaretUp');
	    $searchTab.find('[data-orderfiled="order_timeout_time"]').addClass('myj-active').find('span').addClass('myjCaretUp');
	}
	
	return ;
	MYJ.ajax({
		url: 'package/commSearchList.htm',
		data: {
            state: state,
            isVoided: isVoided,
            isOversea: isOversea,
            commitPlatform: commitPlatform,
            prefixCount: prefixCount,
            newVersion: newVersion,
            history: history,
            isBatch: isBatch,
            isFree: isFree
        },
		success: function (data) {
			$('#commSearchDiv').empty().html(data);

            if(isTimeout === 'timeout'){ //如果是首页点击剩余发货跳到订单页面的,排序方式选中剩余发货时间
                var $searchTab = $('#orderFieldDiv .searchTab');
                $searchTab.find('.myj-active').removeClass('myj-active').find('span').removeClass('myjCaretDown myjCaretUp');
                $searchTab.find('[data-orderfiled="order_timeout_time"]').addClass('myj-active').find('span').addClass('myjCaretUp');
            }
		}
	});
};

/** ajax搜索订单 **/
var searchOrder = function () {
	var state = $("#keepState").data("state");
	if (state == undefined) {
		state = "paid";
	}
	var shopId = $("#keepState").data("shopid");
	if (shopId == undefined || shopId == '') {
		shopId = "-1";
	}
	var searchType = $("#keepState").data("searchtype");
	if (searchType == undefined || searchType == '') {
		searchType = "orderId";
	}
	var authid = $("#keepState").data("authid");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}
	var country = $("#keepState").data("country");
	if (country == undefined || country == '') {
		country = "";
	}
	var platform = $("#keepState").data("platform");
	if (platform == undefined) {
		platform = "";
	}
	var orderfiled = $("#keepState").data("orderfiled");
	if (orderfiled == undefined || orderfiled == '') {
		orderfiled = "order_create_time";
	}
	var search = $("#keepState").data("search");
	if (search == undefined || search == '') {
		search = "0";
	}
    var behindTrack = getBehindState();
    var isOversea = $("#keepState").data("isoversea");
	var isFree = $("#keepState").data("isfree");
	var isBatch = $("#keepState").data("isbatch");
	var content = $("#searchContent").val();		// 搜索内容
	//为了控制每页显示的条数，增加pagesize
	var pageNum = $('#pageSize').val();
	var url = "order/list.htm?pageNo=1&pageSize=" + pageNum + "&shopId=" + shopId + "&state=" + state + "&orderfiled=" + orderfiled + "&searchType=" + searchType + "&content=" + content + "&authId=" + authid + "&country=" + country + "&platform=" + platform + "&search=" + search+"&isOversea="+isOversea+"&isFree="+isFree+"&isBatch="+isBatch+"&behindTrack="+behindTrack;

	$('#loading').modal('show');
	$.ajax({
		type: "GET",
		url: url,
		data: {},
		dataType: "html",
		success: function (data) {
			$('#dxmBody').empty();
			$('#dxmBody').html(data);
			$('#loading').modal('hide');
			$("#searchContent").focus();
			$("#searchContent").select();
		},
		error: function () {
			$('#loading').modal('hide');
			$("#searchContent").focus();
			$("#searchContent").select();
		}
	});
	$("#keepState").data({"ajaxurl": url, "ajaxpostdata": null});
};

/** ajax搜索包裹 **/
var packageList = function (pageNum) {
	// 兼容在搜索状态下点击筛选条件，未带着搜索和高级搜索的条件，分别调用不同的方法去查询
    var $keepState = $('#keepState'),
		selecttype = $keepState.data('selecttype'),
        isAdvanced = $('#isAdvanced').val(),
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

    if (selecttype == 2) {// 搜索
        if (isAdvanced == 1) { // 高级搜索
            advancedSearch();
            return;
        } else { // 普通搜索
            searchPackage();
            return;
        }
    }
	//以下判断条件不要改成===，否则会有问题，参数会不对导致页面查询出来的数据不对
	$keepState.data('orderFlipType', 'packageList');
	var state = $keepState.data('state');
	if (state == undefined) {
		state = 'paid';
	}
	var shopId = $keepState.data('shopid');
	if (shopId == undefined || shopId == '') {
		shopId = '-1';
	}
	var searchType = $keepState.data('searchtype');
	if (searchType == undefined || searchType == '') {
		searchType = 'orderId';
	}
	// 不用
	var authid = $keepState.data('authid');
	if (authid == undefined || authid == '') {
		authid = '-1';
	}
	var search = $keepState.data('search');
	if (search == undefined || search == '') {
		search = '0';
	}
	var startTime = '',
		endTime = '';
	if (state === 'shipped') {
		startTime = $keepState.data('starttime');
		if (startTime == undefined || startTime == '') {
			startTime = '';
		}
		endTime = $keepState.data('endtime');
		if (endTime == undefined || endTime == '') {
			endTime = '';
		}
	}
	var country = $keepState.data('country');
	if (country == undefined || country == '') {
		country = '';
	}
	var orderField = $keepState.data('orderfiled');
	if (orderField == undefined) {
		orderField = 'shipped_time';
	}
	var isVoided = $keepState.data('isvoided');
	if (isVoided == undefined) {
		isVoided = '0';
	}
	var isRemoved = $keepState.data('isremoved');
	if (isRemoved == undefined) {
		isRemoved = '0';
	}
	var platform = $keepState.data('platform');
	if (platform == undefined) {
		platform = '';
	}
	var ruleId = $keepState.data('ruleid');
	if (ruleId == undefined) {
		ruleId = '-1';
	}
	var sysrule = $keepState.data('sysrule');
	if (sysrule == undefined) {
		sysrule = '';
	}
	var applyType = $keepState.data('applytype');
	if (applyType == undefined) {
		applyType = '';
	}
	var applyStatus = $keepState.data('applystatus');
	if (applyStatus == undefined) {
		applyStatus = '';
	}
	var printJh = $keepState.data('printjh');
	if (printJh == undefined) {
		printJh = '-1';
	}
	var printMd = $keepState.data('printmd');
	if (printMd == undefined) {
		printMd = '-1';
	}
	var commitPlatform = $keepState.data('commitplatform');
	if (commitPlatform == undefined) {
		commitPlatform = '';
	}
	var productStatus = $keepState.data('productstatus'),
		jhComment = $keepState.data('jhcomment'),
		storageId = $keepState.data('storageid');
	if (storageId == undefined || storageId == '') {
		storageId = 0;
	}
	var isOversea = $keepState.data('isoversea');
	if (isOversea == undefined || isOversea == '') {
		isOversea = 0;
	}
	var history = $keepState.data('history');
	if (!history) {
		history = '';
	}
	var isFree  = $keepState.data('isfree'),
		isBatch = $keepState.data('isbatch'),
		custom = $keepState.data('custom'),
		timeOut = $('#timeOutHidden').val();
	if(timeOut == undefined){
		timeOut = '0';
	}
	var buyerAccount = $('#buyerAccountHidden').val();
	if(buyerAccount == undefined){
		buyerAccount = '';
	}
	var refundStatus = $keepState.data('refundstatus');
    if (refundStatus == undefined || refundStatus == '') {
        refundStatus = '0';
    }
    var behindTrack = getBehindState();
	var forbiddenStatus = $keepState.data('forbiddenstatus');
	if (forbiddenStatus == undefined || forbiddenStatus == '') {
		forbiddenStatus = '-1';
	}
	var forbiddenReason = $keepState.data('forbiddenreason');
	if (forbiddenReason == undefined || forbiddenReason == '') {
		forbiddenReason = '-1';
	}

	var pageNo = $('#pageNo').val() || 1;
	//为了控制每页显示的条数，增加pagesize
	if(pageNum == undefined){
		pageNum = $('#pageSize').val() || 100;
	}
	var orderId = $('#orderIdHidden').val() || '',
		url = 'package/list.htm?pageNo=' + pageNo + '&pageSize=' + pageNum + '&shopId=' + shopId + '&state=' + state
			+ '&platform=' + platform + '&isSearch=' + search + '&searchType=' + searchType + '&authId=' + authid
			+ '&startTime=' + startTime + '&endTime=' + endTime + '&country=' + country + '&orderField=' + orderField
			+ '&isVoided=' + isVoided + '&isRemoved=' + isRemoved + '&ruleId=' + ruleId + '&sysRule=' + sysrule
			+ '&applyType=' + applyType + '&applyStatus=' + applyStatus + '&printJh=' + printJh
            + '&printMd=' + printMd + '&commitPlatform=' + commitPlatform + '&productStatus=' + productStatus
			+ '&jhComment=' + jhComment + '&storageId=' + storageId + '&isOversea=' + isOversea
			+ '&isFree=' + isFree + '&isBatch=' + isBatch + '&history=' + history
            + '&custom=' + custom + '&timeOut=' + timeOut + '&refundStatus=' + refundStatus
            + '&buyerAccount=' + buyerAccount + '&forbiddenStatus=' + forbiddenStatus
            + '&forbiddenReason=' + forbiddenReason + '&behindTrack=' + behindTrack + '&orderId=' + orderId;

	if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	
	//测试数据
	var data;
	if (state == "allocated_has") {
		//模拟有货
		data = packageListDataHaveData();
	} else {
		data = packageListData();
	}
	$('#dxmBody').empty().html(data);
	if(state === 'approved'){
		/** 查下待处理数据 **/
		refreshCountNum();
	} else {
		refreshApprovedCountNum();
	}
	$('#searchContent').focus().select();
	refreshOrderProfit(0, 'packageId');
	
	//小秘云仓列表批量操作控制
	var orderIsYuncang = $('#orderIsYuncang').val();
	
	if(orderIsYuncang === 'true'){
		orderYuncangListBtnInit();
	}
	refreshStateCount();	// 刷新左侧菜单的统计数字
	
	return;
	MYJ.ajax({
		type: 'GET',
		url: url,
		data: {},
		success: function (data) {
			$('#dxmBody').empty().html(data);
			if(state === 'approved'){
				/** 查下待处理数据 **/
				refreshCountNum();
			} else {
				refreshApprovedCountNum();
			}
            $('#searchContent').focus().select();
            refreshOrderProfit(0, 'packageId');

			//小秘云仓列表批量操作控制
			var orderIsYuncang = $('#orderIsYuncang').val();

			if(orderIsYuncang === 'true'){
				orderYuncangListBtnInit();
			}
			refreshStateCount();	// 刷新左侧菜单的统计数字
		},
		error: function () {
			$('#searchContent').focus().select();
		}
	});
	$keepState.data({'ajaxurl': url, 'ajaxpostdata': null});
};
$(document).ready(function(){
	$(document).on('click','.hoverPrompt.uClick', function(){
		var $wordBox = $(this).find('.word-box');
		$('.hoverPrompt.uClick').find('.word-box').hide();
		$wordBox.is(':hidden') ? $wordBox.show() : $wordBox.hide();
	});
	//鼠标点击位置如果不是.hoverPrompt.uClick;
	$(document).click(function (e) {
		if(!e) var e = window.event;
		//获取事件点击元素
		var targ = e.target;
		var hoverPrompt = $(targ).closest('.hoverPrompt.uClick').length;
		if(+hoverPrompt !== 1) $('.hoverPrompt.uClick').find('.word-box').hide();
	});
});
var refreshOrderProfit = function (type, checkBoxName) {
	var permission = $("#profitPermission").val();

	if(+permission !== 1) return;

	var packageIds = '',
		$state = $('#keepState').data('state');

	if($state === 'refound') return;
	if(+type === 1){ //详情页
		packageIds = checkBoxName;
	}else if(checkBoxName === 'mergedName'){
		$('input[mergedName="mergedName"]').each(function(){
			var v = $(this).val();
			if(packageIds !== '') packageIds += ',';
			packageIds += v;
		});
	}else{
		packageIds = getAllCheckBoxValByName(checkBoxName);
	}
	if(!packageIds || packageIds === '') return;
	
	//测试数据
	var data = getOrderProfit();
	if (data) {
			var showType = data.showType;
			//是否有订单金额权限，boolean类型
			var hasOrderAmountPermission = data.orderAmountPermission;
			$.each(data.data, function (i, j) {
				var profit = j.profit;
				if (+type === 1) {
					var detail = j.amount != null && j.amount !== '' ? '预估利润：CNY ' + profit : '&#12288;&#12288;利润：CNY ' + profit;
					$('#detail_' + i).html(detail);
				} else {
					var $profit = $('#profit_' + i),
						$profitBox = $profit.closest('#profit_' + i + '_box'),
						orderCostStr = '',
						text = '',
						profitStr = '',
						taxAmountStr = '',
						voucherAmountStr = '',
						title = '订单金额 - 平台佣金 - 税费(部分平台包含) - 采购成本 - 预估运费';
					$profit.empty();
	
					if (+profit > 0) {
						profitStr = '<span class="f-orange">￥' + profit + '</span>';
					} else {
						profitStr = '<span class="f-red">￥' + profit + '</span>';
					}
	
					var salesProfitMargin = '', //销售利润率
						costProfitRatio = ''; //成本利润率
	
					if (+j.saleProfitMarginCny) {
						salesProfitMargin = j.saleProfitMarginCny + '%';
					} else {
						salesProfitMargin = '--';
					}
					if (+j.profitMarginCny) {
						costProfitRatio = j.profitMarginCny + '%';
					} else {
						costProfitRatio = '--';
					}
	
					// 税费
					if (j.taxAmount) {
						taxAmountStr += '<tr><td class="p-top0">税费：</td><td class="p-top0"><span class="con">' + j.taxAmount + '</span></td></tr>';
						title += ' - 税费';
					}
					if (j.voucherAmount) {
						voucherAmountStr += '<tr><td class="p-top0">优惠金额：</td><td class="p-top0"><span class="con">' + j.voucherAmount + '</span></td></tr>';
						title += ' - 优惠金额';
					}
					if (j.orderCost != null) {
	                    orderCostStr += '<tr><td class="p-top0">联盟佣金：</td><td class="p-top0"><span class="con">' + j.orderCost + '</span></td></tr>';
	                    title += ' - 联盟佣金';
	                }
					if (j.amount != null && j.amount !== '' && !j.isProfit) {
						var orderAmountTr = '<tr><td class="p-top0">订单金额：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip" data-placement="top" data-trigger="hover" title="同步平台后台订单金额，包含产品售价，部分平台还包含买家支付运费、平台手续费等"></span></td><td class="p-top0"><span class="con">' + j.amount + '</span></td></tr>';
						if (!hasOrderAmountPermission) {
							orderAmountTr = '';
						}
						text = '<table class="order-profit-modal">' +
							'<tbody>' +
	                        '<tr><td class="profit-margin p-top0 p-bottom10 t-right" colspan="2"><a class="gray-b f12" href="' + DXM_HELP_URL + '/pre/getContent.htm?id=839" target="_blank">如何设置预估利润>></a></td></tr>' +
							 orderAmountTr +
							'<tr><td class="p-top0">平台佣金：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
							'data-placement="top" data-trigger="hover" title="Wish、eBay、Amazon、速卖通、Shopee、Lazada 、Tophatter、Fanc 可自动获取手续费；' +
							' 其他平台需前往【用户名】-【系统设置】-【平台手续费】进行设置；' +
							' 如不设置系统默认比例 ：Walmart（15%）、Shopify（0%）、Woocom（0%）、Magento（0%）"></span>' +
							'</td><td class="p-top0"><span class="con">' + j.orderCommission + '</span></td></tr>' +
							orderCostStr + //联盟佣金
							taxAmountStr +
							voucherAmountStr +
							'<tr><td class="p-top0">采购成本：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
							'data-placement="top" data-trigger="hover" title="订单发货仓库的SKU价格"></span>' +
							'</td><td class="p-top0"><span class="con">' + j.cost + '</span></td></tr>' +
							'<tr><td class="p-top0">预估运费：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
							'data-placement="top" data-trigger="hover" title="根据商品重量通过运费模板计算的费用"></span>' +
							'</td><td class="p-top0"><span class="con">' + j.logisticFee + '</span></td></tr>' +
							'<tr><td class="p-top0" colspan="2"><span class="separate"></span></td></tr>' +
							'<tr><td class="p-bottom5">预估利润：<span class="glyphicon glyphicon-question-sign gray-c tooltipHover" data-container="body" data-toggle="tooltip"' +
							'data-placement="top" data-trigger="hover" title="' + title + '"></span></td>' +
							'<td class="p-top0 p-bottom0"><span class="con profit-num p-right10">' + profitStr + '</span></td></tr>' +
	
							'<tr><td class="p-top0 p-bottom0">销售利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + salesProfitMargin + '</span></td></tr>' +
							'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">预估利润/订单金额</td></tr>' +
							'<tr><td class="p-top0 p-bottom0">成本利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + costProfitRatio + '</span></td></tr>' +
							'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">预估利润/(采购成本+预估运费)</td></tr>' +
							'</tbody></table>';
						// $('#p_' + i).text('预估利润:');
						$('#p_' + i).html('<span class="inline-block w22 h22 otherIcon" style="float:left;background-position:-1058px -457px;"></span>');
						$('#unit_' + i).html('￥ ');
						$profit.html(profit);
						if (null == showType || 0 == showType) {
							$("#profitTypeShowDiv_" + i).hide();
						} else {
							if (1 === showType) { // 销售利润率
								$('#pShowTypeVal_' + i).text('「' + salesProfitMargin + '」');
							} else if (2 === showType) { // 成本利润率
								$('#pShowTypeVal_' + i).text('「' + costProfitRatio + '」');
							}
						}
						+profit < 0 ? $profit.addClass('f-red') : '';
						$profitBox.attr('data-content', text);
						$('[data-toggle="tooltip"]').tooltip();
					} else if (profit === '--') {
						//主账号，利润显示关闭处理
						text = '<div class="m-top10"><div class="m-bottom5">显示订单利润功能已关闭！<a href="sys/index.htm?go=m482" target="_blank">前往开启</a></div></div>';
						$('#p_' + i).html('<span class="inline-block w22 h22 otherIcon" style="float:left;background-position:-1058px -457px;"></span>');
						$profit.html(profit);
						$profitBox.attr('data-content', text);
					} else if (profit === '') {
						//子账号，利润显示关闭处理
						$profit.html(profit);
					} else {
						var orderAmountTr = '<tr><td class="p-top0">订单金额：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip" data-placement="top" data-trigger="hover" title="同步平台后台订单金额，包含产品售价，部分平台还包含买家支付运费、平台手续费等"></span></td><td class="p-top0"><span class="con">' + j.amount + '</span></td></tr>';
						if (!hasOrderAmountPermission) {
							orderAmountTr = '';
						}
						//处理hover模态层
					    text ='<table class="order-profit-modal">' +
							'<tbody>' +
							orderAmountTr +
							'<tr><td class="p-top0">平台佣金：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
							'data-placement="top" data-trigger="hover" title="Wish、eBay、Amazon、速卖通、Shopee、Lazada 、Tophatter、Fanc 可自动获取手续费；' +
							' 其他平台需前往【用户名】-【系统设置】-【平台手续费】进行设置；' +
							' 如不设置系统默认比例 ：Walmart（15%）、Shopify（0%）、Woocom（0%）、Magento（0%）"></span>' +
							'</td><td class="p-top0"><span class="con">' + j.orderCommission + '</span></td></tr>' +
							orderCostStr + //联盟佣金
							taxAmountStr +
							voucherAmountStr +
							'<tr><td class="p-top0">采购成本：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
							'data-placement="top" data-trigger="hover" title="订单发货仓库的SKU价格"></span>' +
							'</td><td class="p-top0"><span class="con">' + j.cost + '</span></td></tr>' +
							'<tr><td class="p-top0">运费：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
							'data-placement="top" data-trigger="hover" title="根据商品重量通过运费模板计算的费用"></span>' +
							'</td><td class="p-top0"><span class="con">' + j.logisticFee + '</span></td></tr>' +
							'<tr><td class="p-top0" colspan="2"><span class="separate"></span></td></tr>' +
							'<tr><td class="p-bottom5">利润：' + '</td>' +
							'<td class="p-top0 p-bottom0"><span class="con profit-num p-right10"><span class="f-orange">' + ' CNY ' + profit + '</span></span></td></tr>' +
							'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">来源于【财务-利润核算】的利润</td></tr>' +
							'<tr><td class="p-top0 p-bottom0">销售利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + j.saleProfitMarginCny + ' % ' + '</span></td></tr>' +
							'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">利润/订单金额</td></tr>' +
							'<tr><td class="p-top0 p-bottom0">成本利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + j.profitMarginCny + ' % ' + '</span></td></tr>' +
							'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">利润/(采购成本+物流运费)</td></tr>' +
							'</tbody></table>';
						$('#p_' + i).text('利润:');
						$('#unit_' + i).html('CNY ');
						$profit.html(profit);
						profit < 0 ? $profit.addClass('f-red') : '';
						$profitBox.attr('data-content', text);
					}
				}
			})
		}
	
	return;
	$.ajax({
		type: 'POST',
		url: 'orderProfit/getOrderProfit.json',
		data: {
			packageIds: packageIds
		},
		dataType: 'json',
		success: function (data) {
			if (data) {
				var showType = data.showType;
				//是否有订单金额权限，boolean类型
				var hasOrderAmountPermission = data.orderAmountPermission;
				$.each(data.data, function (i, j) {
					var profit = j.profit;
					if (+type === 1) {
						var detail = j.amount != null && j.amount !== '' ? '预估利润：CNY ' + profit : '&#12288;&#12288;利润：CNY ' + profit;
						$('#detail_' + i).html(detail);
					} else {
						var $profit = $('#profit_' + i),
							$profitBox = $profit.closest('#profit_' + i + '_box'),
							orderCostStr = '',
							text = '',
							profitStr = '',
							taxAmountStr = '',
							voucherAmountStr = '',
							title = '订单金额 - 平台佣金 - 税费(部分平台包含) - 采购成本 - 预估运费';
						$profit.empty();

						if (+profit > 0) {
							profitStr = '<span class="f-orange">￥' + profit + '</span>';
						} else {
							profitStr = '<span class="f-red">￥' + profit + '</span>';
						}

						var salesProfitMargin = '', //销售利润率
							costProfitRatio = ''; //成本利润率

						if (+j.saleProfitMarginCny) {
							salesProfitMargin = j.saleProfitMarginCny + '%';
						} else {
							salesProfitMargin = '--';
						}
						if (+j.profitMarginCny) {
							costProfitRatio = j.profitMarginCny + '%';
						} else {
							costProfitRatio = '--';
						}

						// 税费
						if (j.taxAmount) {
							taxAmountStr += '<tr><td class="p-top0">税费：</td><td class="p-top0"><span class="con">' + j.taxAmount + '</span></td></tr>';
							title += ' - 税费';
						}
						if (j.voucherAmount) {
							voucherAmountStr += '<tr><td class="p-top0">优惠金额：</td><td class="p-top0"><span class="con">' + j.voucherAmount + '</span></td></tr>';
							title += ' - 优惠金额';
						}
						if (j.orderCost != null) {
                            orderCostStr += '<tr><td class="p-top0">联盟佣金：</td><td class="p-top0"><span class="con">' + j.orderCost + '</span></td></tr>';
                            title += ' - 联盟佣金';
                        }
						if (j.amount != null && j.amount !== '' && !j.isProfit) {
							var orderAmountTr = '<tr><td class="p-top0">订单金额：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip" data-placement="top" data-trigger="hover" title="同步平台后台订单金额，包含产品售价，部分平台还包含买家支付运费、平台手续费等"></span></td><td class="p-top0"><span class="con">' + j.amount + '</span></td></tr>';
							if (!hasOrderAmountPermission) {
								orderAmountTr = '';
							}
							text = '<table class="order-profit-modal">' +
								'<tbody>' +
                                '<tr><td class="profit-margin p-top0 p-bottom10 t-right" colspan="2"><a class="gray-b f12" href="' + DXM_HELP_URL + '/pre/getContent.htm?id=839" target="_blank">如何设置预估利润>></a></td></tr>' +
								 orderAmountTr +
								'<tr><td class="p-top0">平台佣金：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
								'data-placement="top" data-trigger="hover" title="Wish、eBay、Amazon、速卖通、Shopee、Lazada 、Tophatter、Fanc 可自动获取手续费；' +
								' 其他平台需前往【用户名】-【系统设置】-【平台手续费】进行设置；' +
								' 如不设置系统默认比例 ：Walmart（15%）、Shopify（0%）、Woocom（0%）、Magento（0%）"></span>' +
								'</td><td class="p-top0"><span class="con">' + j.orderCommission + '</span></td></tr>' +
								orderCostStr + //联盟佣金
								taxAmountStr +
								voucherAmountStr +
								'<tr><td class="p-top0">采购成本：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
								'data-placement="top" data-trigger="hover" title="订单发货仓库的SKU价格"></span>' +
								'</td><td class="p-top0"><span class="con">' + j.cost + '</span></td></tr>' +
								'<tr><td class="p-top0">预估运费：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
								'data-placement="top" data-trigger="hover" title="根据商品重量通过运费模板计算的费用"></span>' +
								'</td><td class="p-top0"><span class="con">' + j.logisticFee + '</span></td></tr>' +
								'<tr><td class="p-top0" colspan="2"><span class="separate"></span></td></tr>' +
								'<tr><td class="p-bottom5">预估利润：<span class="glyphicon glyphicon-question-sign gray-c tooltipHover" data-container="body" data-toggle="tooltip"' +
								'data-placement="top" data-trigger="hover" title="' + title + '"></span></td>' +
								'<td class="p-top0 p-bottom0"><span class="con profit-num p-right10">' + profitStr + '</span></td></tr>' +

								'<tr><td class="p-top0 p-bottom0">销售利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + salesProfitMargin + '</span></td></tr>' +
								'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">预估利润/订单金额</td></tr>' +
								'<tr><td class="p-top0 p-bottom0">成本利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + costProfitRatio + '</span></td></tr>' +
								'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">预估利润/(采购成本+预估运费)</td></tr>' +
								'</tbody></table>';
							// $('#p_' + i).text('预估利润:');
							$('#p_' + i).html('<span class="inline-block w22 h22 otherIcon" style="float:left;background-position:-1058px -457px;"></span>');
							$('#unit_' + i).html('￥ ');
							$profit.html(profit);
							if (null == showType || 0 == showType) {
								$("#profitTypeShowDiv_" + i).hide();
							} else {
								if (1 === showType) { // 销售利润率
									$('#pShowTypeVal_' + i).text('「' + salesProfitMargin + '」');
								} else if (2 === showType) { // 成本利润率
									$('#pShowTypeVal_' + i).text('「' + costProfitRatio + '」');
								}
							}
							+profit < 0 ? $profit.addClass('f-red') : '';
							$profitBox.attr('data-content', text);
							$('[data-toggle="tooltip"]').tooltip();
						} else if (profit === '--') {
							//主账号，利润显示关闭处理
							text = '<div class="m-top10"><div class="m-bottom5">显示订单利润功能已关闭！<a href="sys/index.htm?go=m482" target="_blank">前往开启</a></div></div>';
							$('#p_' + i).html('<span class="inline-block w22 h22 otherIcon" style="float:left;background-position:-1058px -457px;"></span>');
							$profit.html(profit);
							$profitBox.attr('data-content', text);
						} else if (profit === '') {
							//子账号，利润显示关闭处理
							$profit.html(profit);
						} else {
							var orderAmountTr = '<tr><td class="p-top0">订单金额：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip" data-placement="top" data-trigger="hover" title="同步平台后台订单金额，包含产品售价，部分平台还包含买家支付运费、平台手续费等"></span></td><td class="p-top0"><span class="con">' + j.amount + '</span></td></tr>';
							if (!hasOrderAmountPermission) {
								orderAmountTr = '';
							}
							//处理hover模态层
						    text ='<table class="order-profit-modal">' +
								'<tbody>' +
								orderAmountTr +
								'<tr><td class="p-top0">平台佣金：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
								'data-placement="top" data-trigger="hover" title="Wish、eBay、Amazon、速卖通、Shopee、Lazada 、Tophatter、Fanc 可自动获取手续费；' +
								' 其他平台需前往【用户名】-【系统设置】-【平台手续费】进行设置；' +
								' 如不设置系统默认比例 ：Walmart（15%）、Shopify（0%）、Woocom（0%）、Magento（0%）"></span>' +
								'</td><td class="p-top0"><span class="con">' + j.orderCommission + '</span></td></tr>' +
								orderCostStr + //联盟佣金
								taxAmountStr +
								voucherAmountStr +
								'<tr><td class="p-top0">采购成本：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
								'data-placement="top" data-trigger="hover" title="订单发货仓库的SKU价格"></span>' +
								'</td><td class="p-top0"><span class="con">' + j.cost + '</span></td></tr>' +
								'<tr><td class="p-top0">运费：<span class="glyphicon glyphicon-question-sign tooltipHover" data-container="body" data-toggle="tooltip"' +
								'data-placement="top" data-trigger="hover" title="根据商品重量通过运费模板计算的费用"></span>' +
								'</td><td class="p-top0"><span class="con">' + j.logisticFee + '</span></td></tr>' +
								'<tr><td class="p-top0" colspan="2"><span class="separate"></span></td></tr>' +
								'<tr><td class="p-bottom5">利润：' + '</td>' +
								'<td class="p-top0 p-bottom0"><span class="con profit-num p-right10"><span class="f-orange">' + ' CNY ' + profit + '</span></span></td></tr>' +
								'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">来源于【财务-利润核算】的利润</td></tr>' +
								'<tr><td class="p-top0 p-bottom0">销售利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + j.saleProfitMarginCny + ' % ' + '</span></td></tr>' +
								'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">利润/订单金额</td></tr>' +
								'<tr><td class="p-top0 p-bottom0">成本利润率：</td><td class="p-top0 p-bottom0"><span class="con p-right10">' + j.profitMarginCny + ' % ' + '</span></td></tr>' +
								'<tr><td class="p-top0 p-bottom5 gray-a f12" colspan="2">利润/(采购成本+物流运费)</td></tr>' +
								'</tbody></table>';
							$('#p_' + i).text('利润:');
							$('#unit_' + i).html('CNY ');
							$profit.html(profit);
							profit < 0 ? $profit.addClass('f-red') : '';
							$profitBox.attr('data-content', text);
						}
					}
				})
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 搜索包裹 **/
var searchPackage = function () {
    $("#merged").val("");
    $("#splited").val("");
    var state = $("#keepState").data("state");
    if (state == undefined) {
        state = "";
    }
    var orderField = "order_pay_time";
    if($("#keepState").data("orderfiled")!="" && $("#keepState").data("orderfiled")!=undefined){
        orderField=$("#keepState").data("orderfiled");
    }
    var isSearch=$("#keepState").data("search");
    if (isSearch == undefined) {
        isSearch = "";
    }

	// 搜索内容
	var $searchContent = $('#searchContent'),
		orderSearchType = $('#orderSearchType').val(),
		content = $searchContent.val(),
		maxContentNum = $searchContent.attr('data-maxnum') || '',
		hasSpaceWrap = $searchContent.attr('data-spacewrap') || '',
		curContentLen = 0,
		waringText = '',
		searchType = $('#keepState').data('searchtype') || 'orderId';
    // 搜索的最大限制
    if (maxContentNum && content) {
    	if (hasSpaceWrap) {
			content = content.replace(/\s+/g, ',');// 支持空格搜索的转成英文逗号（用于数量限制）
		}
    	content = content.replace(/，/g, ','); // 将中文逗号转换成英文逗号（用于数量限制）
		curContentLen = content.split(',').length;
		if (curContentLen > +maxContentNum) {
			// 修改逻辑是 将多出数量限制的直接去掉 将输入内容变成可搜索的
			var newContent = content.split(',').slice(0, +maxContentNum),
				newStr = newContent.join(',');
			$searchContent.val(newStr);
			content = newStr;

			// switch (+orderSearchType) {
			// 	case 0:
			// 		waringText = '模糊搜索最大搜索条数不能超过30，请使用精确搜索'; // 模糊匹配
			// 		break;
			// 	case 1:
			// 		waringText = '精确搜索最大搜索条数不能超过1000'; // 精确匹配
			// 		break;
			// 	case 2:
			// 		waringText = '完全匹配搜索最大搜索条数不能超过200'; // 完全匹配
			// 		break;
			// }
			// $.fn.message({type: 'error', msg: waringText});
			// return;
		}
	}
    if (searchType == 'sellerComment' && content.trim().length == 1){
		$.fn.message({type: "error", msg: "备注搜索至少需要输入两个非空字符"});
		return;
	}
    var commitPlatform = $("#keepState").data("commitplatform");
    if (commitPlatform == undefined) {
        commitPlatform = "";
    }
    var platform = $("#keepState").data("platform");
    if (platform == undefined) {
        platform = "";
    }
    var shopId = $("#keepState").data("shopid");
    if (shopId == undefined || shopId == '') {
        shopId = "-1";
    }

    var isVoided = $("#keepState").data("isvoided");
    isVoided = isVoided || 0;

    var isRemoved = $("#keepState").data("isremoved");
    isRemoved = isRemoved || 0;

    var history=$("#keepState").data("history");
    if (!history) {
        history = "";
    }
    var behindTrack = getBehindState();
    var isFree  = $("#keepState").data("isfree");
    var isBatch = $("#keepState").data("isbatch");
    var isOversea = $("#keepState").data("isoversea");

	var storageId = $("#keepState").data("storageid");
	if (storageId == undefined || storageId == "") {
		storageId = 0;
	}
    var timeOut = 0;
	/*var timeOut = $("#timeOutHidden").val();
    if(timeOut == undefined){
        timeOut = "0";
    }*/
    //为了控制每页显示的条数，增加pagesize
    var pageNum = $('#pageSize').val();
	if(pageNum == undefined){
		pageNum = 100;
	}
    var isGreen = "";
    var isYellow = "";
    var isOrange = "";
    var isRed = "";
    var isViolet = "";
    var isBlue = "";
    var cornflowerBlue  = "";
    var pink		    = "";
    var teal		    = "";
    var turquoise	    = "";
    var unmarked = "";
    $('#customCommentSearchDiv span.module').each(function () {
        var uid = $(this).attr('uid');
        var dataType = $(this).data('type');
        if (uid == "moduleA"){
            isGreen = dataType;
        }
        if (uid == "moduleB"){
            isYellow = dataType;
        }
        if (uid == "moduleC"){
            isOrange = dataType;
        }
        if (uid == "moduleD"){
            isRed = dataType;
        }
        if (uid == "moduleE"){
            isViolet = dataType;
        }
        if (uid == "moduleF"){
            isBlue = dataType;
        }
        if (uid == "moduleW"){
            cornflowerBlue = dataType;
        }
        if (uid == "moduleX"){
            pink = dataType;
        }
        if (uid == "moduleY"){
            teal = dataType;
        }
        if (uid == "moduleZ"){
            turquoise = dataType;
        }
        if (uid == "moduleI") {
			unmarked = dataType;
		}
    });
    var forbiddenStatus = $("#keepState").data("forbiddenstatus");
    if (forbiddenStatus == undefined || forbiddenStatus == "") {
        forbiddenStatus = "-1";
    }
    var forbiddenReason = $("#keepState").data("forbiddenreason");
    if (forbiddenReason == undefined || forbiddenReason == "") {
        forbiddenReason = "-1";
    }
    var url = "package/searchPackage.htm";
    $('#loading').modal('show');
	var ajaxPostData = {
		pageNo: 1,
		pageSize: pageNum,
		state: state,
		shopId: shopId,
		history: history,
		searchType: searchType,
		content: content,
		isVoided: isVoided,
		isRemoved: isRemoved,
		commitPlatform: commitPlatform,
		platform: platform,
		isGreen: isGreen,
		isYellow: isYellow,
		isOrange: isOrange,
		isRed: isRed,
		isViolet: isViolet,
		isBlue: isBlue,
		cornflowerBlue: cornflowerBlue,
		pink: pink,
		teal: teal,
		turquoise: turquoise,
		unmarked: unmarked,
		isSearch: isSearch,
		isFree: isFree,
		isBatch: isBatch,
		isOversea: isOversea,
		forbiddenStatus: forbiddenStatus,
		forbiddenReason: forbiddenReason,
		orderField: orderField,
		behindTrack: behindTrack,
		storageId: storageId,
		timeOut: timeOut,
		orderSearchType: orderSearchType
	},
	$shopGroupId = $('#shopGroupId'),
	shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) ajaxPostData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	// 隐藏批量添加运单号按钮
	SHOW_BATCHINWAYBILLNO.hideButton();
	// 隐藏批量填充COD按钮
	$('.butchUpdateCOD').addClass('hide');

    $.ajax({
        type: "POST",
        url: url,
		data: ajaxPostData,
        dataType: "html",
        success: function (data) {
            $("#keepState").data("content",content);
            $('#dxmBody').empty();
            $('#dxmBody').html(data);
            $('#loading').modal('hide');
            $("#searchContent").focus();
            $("#searchContent").select();
            refreshOrderProfit(0,'packageId');
        },
        error: function () {
            $('#loading').modal('hide');
            $("#searchContent").focus();
            $("#searchContent").select();
        }
    });
	$("#keepState").data({"ajaxurl": url, "ajaxpostdata": ajaxPostData});
};

var getBehindState = function () {
    var commitPlatform = $("#keepState").data('commitplatform');
    var state = $("#keepState").data('state');
    var behindTrack = $("#keepState").data('behindtrack');
    if (!(state == 'shipped' && (commitPlatform == 'fail' || commitPlatform == 'uncommit')) ) {
        behindTrack = -1;
        $("#keepState").data('behindtrack', -1);
	}
    if (behindTrack === undefined || behindTrack === '') {
        $("#keepState").data('behindtrack', -1);
        behindTrack = "-1";
    }
	return behindTrack;
};

/** 显示高级搜索 **/
var showAdvancedSearch = function(){
	$.ajax({
		type: 'GET',
		url: 'package/advanced.json',
		data: {},
		async: false,
		dataType: 'json',
		success: function (data) {
			var countryList  = data.countryList,
				warehoseList = data.warehoseList || [],
				shipReciverWarehouseList = data.shipReciverWarehouseList,
				shipReciverOptions =  '<option value="0">--请选择--</option>',
				countryOptions = '<option value="">--请选择--</option>';
			setAdvSearchType(0, $('#advSearchType').val('orderId'));
			$('.orderAdvSearchType').val(1); // 精确匹配
			$('#advSearchContent').val('').attr({
				'placeholder': '多个订单号间用逗号或空格隔开，最多支持1000个',
				'data-maxnum': 1000
			});
			for(var i=0;i<countryList.length;i++){
                countryOptions += '<option value="'+ countryList[i].code +'">'+countryList[i].countryCh+'（'+countryList[i].countryEn+' - '+countryList[i].code+'）</option>';/*添加内容方便搜索*/
			}
            $('#advancedCountrySelect').empty().append(countryOptions);
			$('#advancedStorageSelect').commonMoreSelect({
				list: warehoseList,
				selAll: true,
				hasCheckSearch: true,
				defaultTitle: '--请选择--',
				callBack: function (dataObj) {
					var supplierResultArr = [];
					$.each(dataObj, function (key, val) {
						supplierResultArr.push(dataObj[key].id);
					});
					$('input[name="storageIds"]').val(supplierResultArr.join(','));
					commonSearchSave.removeSearchModalActiveClass();
				}
			}, 'init');
			$('input[name="storageIds"]').val('');

			// 展示epc仓库删选
			for(var i=0;i<shipReciverWarehouseList.length;i++){
				shipReciverOptions += '<option value="'+ shipReciverWarehouseList[i].warehouseCode +'">'+ shipReciverWarehouseList[i].warehouseName +'</option>';
			}
			$('#advancedShipReciverSelect').empty().append(shipReciverOptions);

			//搜索插件调用 start
			$('.chosen-select').chosen('destroy').chosen({
				search_contains: true//注册插件\
			});
			$('.chosen-container').css('width','180px');
			$('#advancedCountrySelect_chosen').css('width','180px');
			$('.chosen-drop').css('width','302px');
			$('.chosen-search').find('input').attr('placeholder','支持中文、英文、二字码搜索');
			//end
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	$("#searchDiv").css("display","none");
	$("#searchTypeDiv").css("display","none");
	$("#advancedSearchDiv").css("display","");
};

/** 取消高级搜索 **/
var cancelAdvanced = function(){
	$("#searchDiv").css("display","");
	$("#searchTypeDiv").css("display","");
	$("#advancedSearchDiv").css("display","none");
	resetAdvanced();
};

/** 高级搜索重置 **/
var resetAdvanced = function(){
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	$('input[name="priceStart"]').val('');
	$('input[name="priceEnd"]').val('');
	$('input[name="orderCreateStart"]').val('');
	$('input[name="orderCreateEnd"]').val('');
	$('input[name="orderPayStart"]').val('');
	$('input[name="orderPayEnd"]').val('');
	$('input[name="shippedStart"]').val('');
	$('input[name="shippedEnd"]').val('');
	$('input[name="refundedStart"]').val('');
	$('input[name="refundedEnd"]').val('');
	$('input[name="mdSignStart"]').val('');
	$('input[name="mdSignEnd"]').val('');
	$('input[name="jhSignStart"]').val('');
	$('input[name="jhSignEnd"]').val('');
	$('input[name="productCountStart"]').val('');
	$('input[name="productCountEnd"]').val('');
	$('input[name="timeOut"]').val('');
	$('input[name="timeOutQuery"][value="-1"]').prop('checked', true);
	$('input[name="productStatus"]').prop('checked', false);
	$('input[name="isHasPickComment"]').prop('checked', false);
	$('input[name="days"][value="-1"]').prop('checked', true);
	$('input[name="isPrintJh"][value="-1"]').prop('checked',true);
	$('input[name="signPriorShip"][value="-1"]').prop('checked', true);
	$('input[name="isPrintJhTemp"][value="-1"]').prop('checked',true);
	$('input[name="isPrintMd"][value="-1"]').prop('checked',true);
	$('input[name="commitPlatform"][value=""]').prop('checked',true);
	$('input[name="isHasOrderMessage"][value="-1"]').prop('checked',true);
	$('input[name="isHasOrderComment"][value="-1"]').prop('checked',true);
	$('input[name="isHasServiceComment"][value="-1"]').prop('checked',true);
	$('input[name="isHasPickComment"][value="-1"]').prop('checked',true);
	$('tr.pickCommentColorTr').removeClass('hide');
	$('input[name="globalCollection"][value="-1"]').prop('checked',true);
	$('#advancedCountrySelect').val('');
	$('#advancedShipReciverSelect').val(0);
	$('#advancedStorageSelect').trigger('selectMenu:clear');
	$('#advancedAuthSelect').val(-1);
	$('#advancedAuthSelect').trigger("chosen:updated");
    $('#customCommentAdvenceSearchDiv').find('.module').each(function(){
		if($(this).data('type') == 1){
			$(this).click();
		}
    });
	//重置拣货说明
	$('#pickingInstructionsDiv').find('.module').each(function(){
		if($(this).data('type') == 1){
			$(this).click();
		}
	});
	$('#pickingInstructions').val('');
    $('#advancedCountrySelect_chosen').find('span').html('请选择'); // 重置国家
    $('#addContent').find('input').prop('checked',false); // 重置附加信息

	//切换完后再走一遍搜索类型的方法，重新更正下搜索框展示样式
	var objDivNum = $('.dataTypeClick').find('.rightTabActive').attr('data-type'),
		$activeA = $('.orderSearchType').find('a.myj-active');

	if (+objDivNum === 2) setSearchType($activeA.attr('data-name'), $activeA);
};

//实时更新拣货说明参数值
var updatePickingInstructionsData = function () {
//拣货说明参数
	var picking='';
	$('#pickingInstructionsDiv span.module').each(function () {
		var dataType = $(this).data('type');
		if (dataType === 1){
			if (picking === ''){
				picking = $(this).data('val');
			} else {
				//多个颜色值之间使用英文逗号隔开
				picking = picking.concat(',',$(this).data('val'));
			}
		}
	});
	$('#pickingInstructions').val(picking);
};

/** 高级搜索 **/
var advancedSearch = function(){
	var reg = /^\d+(\.\d{1,2})?$/,
		priceStart = $("input[name='priceStart']").val(),
		priceEnd   = $("input[name='priceEnd']").val(),
		productCountStart = $("input[name='productCountStart']").val(),
		productCountEnd   = $("input[name='productCountEnd']").val();

	if (priceStart && !reg.test(priceStart)) {
		$.fn.message({type: "error", msg: "订单金额请输入大于0的数字,小数点保留1-2位"});
		$("input[name='priceStart']").focus();
		return;
	}
	if (priceEnd && !reg.test(priceEnd)) {
		$.fn.message({type: "error", msg: "订单金额请输入大于0的数字,小数点保留1-2位"});
		$("input[name='priceEnd']").focus();
		return;
	}
	var regs = /^[0-9]*$/;
	if (productCountStart && !productCountStart.match(regs)) {
		$.fn.message({type: "error", msg: "订单商品数量请输入大于0的整数"});
		$("input[name='productCountStart']").focus();
		return;
	}
	if (productCountEnd && !productCountEnd.match(regs)) {
		$.fn.message({type: "error", msg: "订单商品数量请输入大于0的整数"});
		$("input[name='productCountEnd']").focus();
		return;
	}

	var advancedSearchType = $('#advSearchType').val(), // 高级搜索 输入框 搜索类型
		$advancedSearchInput = $('#advSearchContent'), // 高级搜索 输入框
		advancedSearchVal = $.trim($advancedSearchInput.val()), // 输入内容
		maxContentNum = $advancedSearchInput.attr('data-maxnum') || '',
		hasSpaceWrap = $advancedSearchInput.attr('data-spacewrap') || '',
		curContentLen = 0,
		waringText = '',
		orderAdvSearchType = $('#orderAdvSearchType').val(); // 高级搜索 匹配类型

	//校验备注的内容
	if (advancedSearchType === 'sellerComment' && advancedSearchVal.length === 1) {
		$.fn.message({type: 'error', msg: '备注搜索至少需要输入两个非空字符'});
		return;
	}

	// 搜索输入框数量限制
	if (maxContentNum && advancedSearchVal) {
		if (hasSpaceWrap) {
			advancedSearchVal = advancedSearchVal.replace(/\s+/g, ',');// 支持空格搜索的转成英文逗号（用于数量限制）
		}
		advancedSearchVal = advancedSearchVal.replace(/，/g, ','); // 将中文逗号转换成英文逗号（用于数量限制）
		curContentLen = advancedSearchVal.split(',').length;
		if (curContentLen > +maxContentNum) {
			switch (+orderAdvSearchType) {
				case 0:
					waringText = '模糊搜索最大搜索条数不能超过30，请使用精确搜索'; // 模糊匹配
					break;
				case 1:
					waringText = '精确搜索最大搜索条数不能超过1000'; // 精确匹配
					break;
				case 2:
					waringText = '完全匹配搜索最大搜索条数不能超过200'; // 完全匹配
					break;
			}
			$.fn.message({type: 'error', msg: waringText});
			return;
		}
	}

	var $keepState = $('#keepState'),
        state = $keepState.data('state'),
        isVoided = $keepState.data('isvoided');
	isVoided = isVoided || 0;

	var isRemoved = $keepState.data('isremoved');
	isRemoved = isRemoved || 0;

	var commitPlatform = $keepState.data('commitplatform');
	if (!commitPlatform) {
		commitPlatform = '';
	}
	var platform = $keepState.data('platform');
	if (!platform) {
		platform = '';
	}
	var shopId = $keepState.data('shopid');
	if (!shopId) {
		shopId = '-1';
	}
	var isOversea = $keepState.data('isoversea'),
        history = $keepState.data('history');
	if(!history){
		history = '';
	}
    var isDesc = $keepState.data('search');
    if (!isDesc) {
        isDesc = '0';
    }
    var orderField = $keepState.data('orderfiled');
    if (!orderField) {
        orderField = '';
    }

    //var timeOut = $('#timeOutHidden').val();
    var timeOut = 0;

    // 因为仓库id在筛选中和高级搜索中有冲突，所以高级搜索为空，以筛选的为准。高级搜索不为空，以高级搜索的为准
    var storageId = $('#keepState').data('storageid'), // 列表筛选
        advStorageIds = $('input[name="storageIds"]').val(); // 高级搜索多选仓库
    if (advStorageIds !== '0' && Boolean(advStorageIds)) {
		$('input[name="storageIds"]').removeClass('hide'); // form表单自动取值，后端字段改为storageIds，传storageId也可以（兼容原来的）
		$('input[name="storageId"]').val('').addClass('hide');
	} else {
		$('input[name="storageIds"]').val('').addClass('hide');
		$('input[name="storageId"]').val(storageId).removeClass('hide');
	}

    $('#advancedTimeOut').val(timeOut);
	$('#advancedState').val(state);
	$('#advancedVoided').val(isVoided);
	$('#advancedRemoved').val(isRemoved);
	$('#advancedCommitPlatform').val(commitPlatform);
	$('#advancedIsOversea').val(isOversea);
	$('#advancedShopId').val(shopId);
	$('#advancedPlatform').val(platform);
	$('#advancedHistory').val(history);
	$('#advanceOrderField').val(orderField); // 排序字段
	$('#advanceIsDesc').val(isDesc); // 是否降序

    var isGreen = '',
    	isYellow = '',
    	isOrange = '',
    	isRed = '',
    	isViolet = '',
    	isBlue = '',
    	cornflowerBlue = '',
    	pink = '',
    	teal = '',
    	turquoise = '',
		unmarked = '';
    $('#customCommentAdvenceSearchDiv span.module').each(function () {
        var uid = $(this).attr('uid');
        var dataType = $(this).data('type');
        if (uid === 'moduleA'){
            isGreen = dataType;
        }
        if (uid === 'moduleB'){
            isYellow = dataType;
        }
        if (uid === 'moduleC'){
            isOrange = dataType;
        }
        if (uid === 'moduleD'){
            isRed = dataType;
        }
        if (uid === 'moduleE'){
            isViolet = dataType;
        }
        if (uid === 'moduleF'){
            isBlue = dataType;
        }
        if (uid === 'moduleW'){
            cornflowerBlue = dataType;
        }
        if (uid === 'moduleX'){
            pink = dataType;
        }
        if (uid === 'moduleY'){
            teal = dataType;
        }
        if (uid === 'moduleZ'){
            turquoise = dataType;
        }
        if (uid === 'moduleI') {
			unmarked = dataType;
		}
    });

    var forbiddenStatus = $keepState.data('forbiddenstatus');
    if (!forbiddenStatus) {
        forbiddenStatus = '-1';
    }
    var forbiddenReason = $keepState.data('forbiddenreason');
    if (!forbiddenReason) {
        forbiddenReason = '-1';
    }
    $('#advancedIsGreen').val(isGreen);
    $('#advancedIsYellow').val(isYellow);
    $('#advancedIsOrange').val(isOrange);
    $('#advancedIsRed').val(isRed);
    $('#advancedIsViolet').val(isViolet);
    $('#advancedIsBlue').val(isBlue);
    $('#advancedCornflowerBlue').val(cornflowerBlue);
    $('#advancedPink').val(pink);
    $('#advancedTeal').val(teal);
    $('#advancedTurquoise').val(turquoise);
    $('#advancedUnmarked').val(unmarked);
    $('#advancedForbiddenStatus').val(forbiddenStatus);
    $('#advancedForbiddenReason').val(forbiddenReason);
	updatePickingInstructionsData();//更新下拣货说明参数
    //为了控制每页显示的条数，增加pagesize
    var pageNum = $('#pageSize').val() || 100,
        serializeArray = $('#advancedForm').serializeArray(), //获取到form表单中所有需要提交的数据，这是一个[{name:'key',value:'value'}]的格式的数据
        serialize = [], //获取高级搜索form表单需要提交的数据
        serializeLen = 0, //获取包裹类型的checkbox的name值对应数组的下标
        isProductStatus = {}, //用来判断包裹类型是否已经push到数组中
		getHasPickComment = function (arr) {
    		var isHasPickComment = true;
			$.each(arr, function (m, n) {
				if (n.name === 'isHasPickComment' && !+n.value) {
					isHasPickComment = false;
					return false;
				}
			});
			return isHasPickComment;
		}; //用来判断包裹类型是否已经push到数组中
	$.each(serializeArray, function (i, j) {	// 循环数据，因为form表单提交checkbox的值是无法自动逗号拼接，所以需要循环处理一下
		if (j.name === 'productStatus') {	// 如果当前name=productStatus
			if (isProductStatus[j.name]) {	// 判断对象key = 'productStatus'的value是否为true
				// 找到数组对应下标的值，进行逗号拼接value，最后这个下标的值会是productStatus=xx,xx,xx
				serialize[serializeLen] += (serialize[serializeLen].split('=')[1] ? ',' : '') + j.value;
			} else {	// 如果不为true
				serialize.push(j.name + '=' + j.value);	// 先直接赋值
				serializeLen = serialize.length - 1;	// 获取当前数组长度
				isProductStatus[j.name] = true;	// 给对象key = 'productStatus' 的value赋值为true
			}
		} else {	// 如果不等于则直接把name和value拼接
			// 无拣货备注时置空 pickingInstructions
			if (j.name === 'pickingInstructions') {
				if (!getHasPickComment(serializeArray)) j.value = '';
			}
			serialize.push(j.name + '=' + encodeURIComponent(j.value));
		}
	});
	serialize.push('pageNo=1');
	serialize.push('pageSize=' + pageNum);
	var url = 'package/advancedSearch.htm';
	var ajaxPostData = serialize.join('&'),
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) ajaxPostData += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件

	// 显示批量添加国内运单号
	SHOW_BATCHINWAYBILLNO.showButton();

	$('#loading').modal('show');
	$.ajax({
		type: 'POST',
		url: url,
		data: ajaxPostData, //把处理之后的数据使用&拼接成字符串
		dataType: 'html',
		success: function (data) {
			$('#dxmBody').empty().html(data);
			$('#loading').modal('hide');
            refreshOrderProfit(0,'packageId');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	$keepState.data({"ajaxurl": url, "ajaxpostdata": ajaxPostData});
};

/*切换高级搜索的默认文本*/
var setAdvSearchType = function (typeNum, obj) {
	var $advSerachDiv = $(obj).closest('.advSerachDiv'),
		type = $advSerachDiv.find('.advSearchType').val();

	advSearchSelShow();//高级搜索框显示、隐藏处理

	if (!+typeNum) {
		var $advSearchContent = $('#advSearchContent'),
			$orderAdvSearchType = $advSerachDiv.find('.orderAdvSearchType'),
			orderAdvSearchType = $orderAdvSearchType.val(),
			maxNumText;
		if(!$orderAdvSearchType.is(':visible'))orderAdvSearchType = 1; // 禁用匹配方式就默认精确匹配
		switch (+orderAdvSearchType) {
			case 0:
				maxNumText = 30; // 模糊匹配
				break;
			case 1:
				maxNumText = 1000; // 精确匹配
				break;
			case 2:
				maxNumText = 200; // 完全匹配
				break;
		}
		$advSearchContent.attr({
			'data-maxnum': maxNumText, // 最大数量限制
			'data-spacewrap': true // 是否支持空格分隔
		});
		if(type === 'orderId') {
			$advSearchContent.attr('placeholder', '多个订单号间用逗号或空格隔开，最多支持' + maxNumText + '个');
		} else if(type === 'packageNum') {
			$advSearchContent.attr('placeholder', '多个包裹号间用逗号或空格隔开，最多支持' + maxNumText + '个');
		} else if(type === 'trackNum') {
			$advSearchContent.attr({
				'placeholder': '多个跟踪号间用逗号或空格隔开，最多支持' + maxNumText + '个'
			});
		} else if(type === 'platformSku') {
			$advSearchContent.attr('placeholder', '多个平台SKU间用逗号隔开，最多支持' + maxNumText + '个');
		} else if (type === 'extendedOrderId') {
			$advSearchContent.attr('placeholder', '多个平台编号间用逗号或空格隔开，最多支持' + maxNumText + '个');
		} else {
			$advSearchContent.attr({
				'placeholder': '',
				'data-maxnum': '',
				'data-spacewrap': ''
			});
		}
	}

	var $thatSearchIpt = $(obj).closest('.advSerachDiv').find('[name="contents"]'),
		isReplaceEmoji = false,
		searchTypeArr = ['orderId', 'packageNum', 'trackNum', 'productSku', 'productId', 'email'];

	if (searchTypeArr.indexOf(type) !== -1) {
		isReplaceEmoji = true;
	}
	$thatSearchIpt.off('input.replaceEmoji');
	if (isReplaceEmoji) {
		inputEmptyEmojiCode($thatSearchIpt);
		$thatSearchIpt.on('input.replaceEmoji', function () {
			inputEmptyEmojiCode(this);
		});
	}
};

/*精确、模糊搜索下拉框显示和隐藏处理，只有订单号、包裹号、跟踪号、平台SKU支持添加精确匹配和模糊匹配功能，
* 并且只有第一个符合条件的类型后面的下拉框可以操作*/
var advSearchSelShow = function () {
	//循环处理下右侧的下拉框，针对固定的几个类型显示精确和模糊搜索的下拉框，且只能在第一个的时候支持可修改
	var addAdvSearchType = ['orderId', 'packageNum', 'trackNum', 'platformSku'],//订单号、包裹号、跟踪号、平台SKU支持添加精确匹配和模糊匹配功能
		flag = false;

	$('.advSerachDiv').each(function () {
		var $advSearch = $(this).find('.orderAdvSearchType'),
			$searchType = $(this).find('select.advSearchType'),
			selVal = $searchType.val();

		$advSearch[addAdvSearchType.indexOf(selVal) !== -1 ? 'removeClass' : 'addClass']('hide');//如果是需要精确和模糊搜索的那些类型，先显示下拉框
		if (!flag && addAdvSearchType.indexOf(selVal) !== -1) {//第一个可支持精确和模糊搜索的节点，放开禁用
			$advSearch.attr('name', 'orderAdvSearchType').prop('disabled', false);
			flag = true;
		} else {
			$advSearch.removeAttr('name').prop('disabled', true);
		}
	});
	//处理添加搜索类型时，下拉框内容不一致的情况
	var $advSearch = $('.orderAdvSearchType:visible').first(),
		defaultVal = $advSearch.val();

	if ($advSearch.length && !$advSearch.is(':disabled')) $('.orderAdvSearchType').val(defaultVal);
};

/** 查询可合并订单列表 **/
var getMergeOrderList = function (val, obj) {
	$("#merged").val("merged");
	$("#splited").val("");
	$("#batchMergeBtn").css("display", "");
	$("#batchMergeBtn1").css("display", "");
	$("#batchBtnDiv").css("display", "none");
	$("#batchBtnDiv1").css("display", "none");
	$("#moveProcessBtn").css("display", "none");
	$("#moveProcessBtn1").css("display", "none");

	setClass(obj);
	$('#loading').modal('show');
	var state = $("#keepState").data("state");
	if (state == undefined) {
		state = "approved";
	}
	var shopId = $("#keepState").data("shopid");
	if (shopId == undefined || shopId == '') {
		shopId = "-1";
	}
	var authid = $("#keepState").data("authid");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}
	var custom = $("#keepState").data("custom");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}
	var param = getOneThousandParaData();
	var pageNum = ORDER_STORAGE_SET.get('pageSize');
	pageNum = pageNum || $('#pageSize').val() || 100;
	var url = "package/mergeList.htm?pageNo=0&pageSize=" + pageNum + "&shopId=" + shopId + "&state=" + state + "&authId=" + authid + "&custom="+custom;
    url = url + "&platform=" + param.platform+"&country="+param.country+"&orderField="+param.orderField +"&isDesc="+param.isSearch;
	if (param.shopGroupId) url += '&shopGroupId=' + param.shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$.ajax({
		type: "GET",
		url: url,
		data: {},
		dataType: "html",
		success: function (data) {
			$('#dxmBody').empty();
			$('#dxmBody').html(data);
			$('#loading').modal('hide');
            refreshOrderProfit(0,"mergedName");
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	$("#keepState").data({"ajaxurl": url, "ajaxpostdata": null});
	$('.operationClear').click(); // 清空选中1000条
};

/** 查询已合并订单列表 **/
var getSplitOrderList = function (val, isMerge, obj) {
	$("#merged").val("");
	$("#splited").val("");
	$("#batchMergeBtn").css("display", "none");
	$("#batchMergeBtn1").css("display", "none");
	$("#keepState").data("isMerge",isMerge);
	if (isMerge == 1) {
		$("#moveProcessBtn").css("display", "block");
		$("#moveProcessBtn1").css("display", "block");
		$("#batchBtnDiv").css("display", "block");
		$("#batchBtnDiv1").css("display", "block");
	} else if (isMerge == 0) {
		$("#moveProcessBtn").css("display", "");
		$("#moveProcessBtn1").css("display", "");
		$("#batchBtnDiv").css("display", "");
		$("#batchBtnDiv1").css("display", "");
	}
	setClass(obj);
	$('#loading').modal('show');
	var state = $("#keepState").data("state");
	if (state == undefined) {
		state = "approved";
	}
	var shopId = $("#keepState").data("shopid");
	if (shopId == undefined || shopId == '') {
		shopId = "-1";
	}
	var authid = $("#keepState").data("authid");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}
	var custom = $("#keepState").data("custom");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}

	var pageNum = ORDER_STORAGE_SET.get('pageSize');
	pageNum = pageNum || $('#pageSize').val() || 100;

	var param = getOneThousandParaData(); // 为了得到参数
	var url = "package/splitList.htm?pageNo=0&pageSize=" + pageNum + "&shopId=" + shopId + "&state=" + state + "&authId=" + authid + "&isMerge=" + isMerge+"&custom="+custom;
	url = url + "&platform=" + param.platform+"&country="+param.country+"&orderField="+param.orderField +"&isDesc="+param.isSearch;
	if (param.shopGroupId) url += '&shopGroupId=' + param.shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$.ajax({
		type: "GET",
		url: url,
		data: {},
		dataType: "html",
		success: function (data) {
			$('#dxmBody').empty();
			$('#dxmBody').html(data);
			$('#loading').modal('hide');
            refreshOrderProfit(0,'packageId');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	$("#keepState").data({"ajaxurl": url, "ajaxpostdata": null});
	$('.operationClear').click(); // 清空选中1000条
};

/** 已拆分订单列表 **/
var getSplitedOrderList = function(obj){
	$("#merged").val("");
	$("#splited").val("splited");
	$("#batchMergeBtn").css("display", "none");
	$("#batchMergeBtn1").css("display", "none");
	$("#moveProcessBtn").css("display", "none");
	$("#moveProcessBtn1").css("display", "none");
	$("#batchBtnDiv").css("display", "none");
	$("#batchBtnDiv1").css("display", "none");
	setClass(obj);
	$('#loading').modal('show');
	var state = $("#keepState").data("state");
	if (state == undefined) {
		state = "approved";
	}
	var shopId = $("#keepState").data("shopid");
	if (shopId == undefined || shopId == '') {
		shopId = "-1";
	}
	var authid = $("#keepState").data("authid");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}
	var custom = $("#keepState").data("custom");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}
	var param = getOneThousandParaData();
	var pageNum = $('#pageSize').val() || 100;
	var url = "order/splitedList.htm?pageNo=0&pageSize=" + pageNum + "&shopId=" + shopId + "&state=" + state + "&authId=" + authid+"&custom="+custom;
    url = url + "&platform=" + param.platform+"&country="+param.country+"&orderField="+param.orderField +"&isDesc="+param.isSearch;
	if (param.shopGroupId) url += '&shopGroupId=' + param.shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$.ajax({
		type: "GET",
		url: url,
		data: {},
		dataType: "html",
		success: function (data) {
			$('#dxmBody').empty();
			$('#dxmBody').html(data);
			$('#loading').modal('hide');
            refreshOrderProfit(0,"mergedName");
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	$("#keepState").data({"ajaxurl": url, "ajaxpostdata": null});
	$('.operationClear').click(); // 清空选中1000条
};

/** 检验shopee拆分订单规则 **/
var checkShopeeSplitedOrder = function (packageId, platform) {
	$('#loading').modal('show');
	var flag = false;
	$.ajax({
		type: "POST",
		url: 'order/checkShopeeSplitedOrder.json',
		data: {"packageId": packageId, "platform": platform},
		async: false,
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				flag = true;
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
			showNetError();
		}
	});
	return flag;
};

var showNetError = function(){
	$.fn.message({type: "error", msg: "网络异常，请稍后重试"});
}

/** 拆分订单详情 **/
var splitedOrderDetail = function (packageId, platform, callback) {
	if("wish" == platform){
		myjAlert.alert({
			'content':'wish平台不支持上传多个运单号，拆分后会将第一个点击发货的「运单号」提交平台，剩余运单号单号不提交平台',
			'enter' :'我知道了'
		});
	}else if ("shopyy" == platform) {
		myjAlert.alert({
			'content':'shopyy平台拆分后第一个订单点击发货会将平台订单状态置为全部发货，同步将不更新剩余未发货订单信息',
			'enter' :'我知道了'
		});
	}else if ("shopee" == platform) {
		if (!checkShopeeSplitedOrder(packageId, "shopee")) {
			return;
		}
		myjAlert.alert({
			'content':'因Shopee接口限制，仅支持按照SKU级别拆分，不支持按照数量拆分，因此在填写包裹内产品数量时需填写产品总数。一个订单最多可拆分为5个包裹',
			'enter' :'我知道了'
		});
	}
	var type = 0;
	if ("ebay" === platform || "shopify" === platform || "amazon" === platform || "smt" === platform || "wish" === platform
		|| "lazada" === platform || "shopyy" === platform || "shopbase" === platform || "daraz" === platform || "shein"=== platform
		|| "fruugo"=== platform || "shopee" === platform || "onbuy"===platform  || "shopline2" === platform || "dh" === platform) {
		type = 1; // 批量拆分优先使用，部分平台拆分需要调用平台接口批量复杂，type=0
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/splitedOrderDetail.htm',
		data: {"packageId": packageId, "type": type},
		dataType: "html",
		success: function (data) {
			$('#loading').modal('hide');
			$('#splitedOrderDetailDiv').empty();
			$('#splitedOrderDetailDiv').html(data);
			$('#splitOrderDetailModal').modal('hide');
			$('#splitOrderDetailModal').modal('show');
			if (callback != undefined && callback != '') {
				callback();
			}
			if (type === 1) BATCH_SPLITED_ORDER.modalShowHandle(platform);//如果是eBay批量拆分，则做下显示的处理
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 选中拆分事件 **/
var splitedCheck = function(obj, platform, productCount) {
	if (platform == 'shopee' || platform == 'shoplazza' || platform == 'daraz' || platform == 'tiktok' || platform == 'walmart' || platform == 'aliArise') {
		if ($(obj).is(":checked")) {
			$(obj).parent().parent().find("input[name='num']").val(productCount);
		} else {
			$(obj).parent().parent().find("input[name='num']").val('');
		}
		if (platform == 'shoplazza' || platform == 'daraz' || platform == 'walmart' || platform == 'aliArise') {
			getSplitSkuNum();
		}
	} else {
		if($(obj).is(":checked")){
			$(obj).parent().parent().find("input[name='num']").attr("readOnly",false);
		} else {
			$(obj).parent().parent().find("input[name='num']").attr("readOnly",true);
		}
	}
};
/** 获取拆分订单的数量 **/
var getSplitSkuNum = function(){
	var skuNum = 0;
	var orderCount = 0;
	$("input[name='isSplit']:checked").each(function(){
		var num = $(this).parent().parent().find("input[name='num']").val();
		orderCount += parseInt(num);
		skuNum++;
	});
	$("#splitNewOrderSkuNum").text(skuNum);
	$("#splitNewOrderCount").text(isNaN(orderCount) ? "0" : orderCount);
};

/** 拆分订单 **/
var splitOrder = function (platform) {

	var orderNums = new Array();
	$("input[name='isSplit']:checked").each(function(){
		var obj = $(this).parent().parent().find("input[name='num']");
		orderNums.push(obj);
	});
	if(orderNums.length == 0){
		if ('shopee' == platform ||'tiktok' == platform || 'shoplazza' == platform || 'walmart' == platform || 'aliArise' == platform) {
			$.fn.message({type: "error", msg: "请选择一个商品拆分"});
		} else {
			$.fn.message({type: "error", msg: "请选择一个商品拆分并输入数量"});
		}
		return;
	}
	var b = validateCustom(orderNums, /^[0-9]*$/, 1, "请输入数量", "数量请输入大于0的整数");
	if (b) {
		return;
	}
	var isSplit = '';
	$("#splitOrderForm").find("input[name='isSplit']").each(function(){
		var num = 0;
		if($(this).is(":checked")){
			num = 1;
		}
		if(isSplit == ''){
			isSplit += num;
		} else {
			isSplit += ',' + num;
		}
	});
	$("#isSplitStr").val(isSplit);
	$('#loading').modal('show');

	$.ajax({
		type: "POST",
		url: 'order/splitOrder.json',
		data: $("#splitOrderForm").serialize(),
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单拆分成功！"});
				$('#packageDetailModal').modal('hide');
				$('#splitOrderDetailModal').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
				$('#splitOrderDetailModal').modal('hide');
				$('#splitOrderDetailModal').modal('show');
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 弹窗显示合并订单 **/
var showMergeOrder = function (key, platform) {
	$('#loading').modal('show');
	var packageIds = getAllCheckBoxValByName("packageId" + key);
	$.ajax({
		type: "POST",
		url: 'package/getByPackageIds.htm',
		data: {"packageIds": packageIds},
		dataType: "html",
		success: function (data) {
			var $mergeOrderModal = $('#mergeOrderModal');
			$('#mergeOrderTable').html(data);
			$('#loading').modal('hide');

			//如果是Shopee平台的合并操作，则直接全部勾选上，然后再去执行合并操作
			if (platform === 'shopee') {
				var $input = $mergeOrderModal.find('input[name="dxmPackageIdName"]');

				if ($input.length) {
					$input.prop('checked', true);
					mergeOrder(1);
				} else {
					MYJ.message.error('暂时无可合并的订单');
				}
			} else {
				$mergeOrderModal.modal('hide').modal('show');
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 执行合并订单 **/
var executeMergeOrder = function(packageIds,addrId){
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/mergeOrder.json',
		data: {"packageIds": packageIds, "addrId":addrId},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "合并订单成功!"});
				$('#mergeOrderModal').modal('hide');
				refreshAjaxPage();

			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 合并订单 **/
var mergeOrder = function (isShow, key) {

	var packageIds = "";
	if (isShow == 1) {
		/** 可以合并的包裹多余2个，需要弹框选择 **/
		packageIds = getCheckBoxValByName("dxmPackageIdName");
	} else {
		/** 直接合并包裹 **/
		packageIds = getAllCheckBoxValByName("packageId" + key);
	}
	if (packageIds == '' || packageIds == null) {
		$.fn.message({type: "error", msg: "请选择要合并的订单!"});
		return;
	}

	$.ajax({
		type: "POST",
		url: 'order/isAddrEqual.json',
		data: {"packageIds": packageIds},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				/** 执行合并操作 **/
				executeMergeOrder(packageIds);
			} else {
				/** 弹出地址不同提示框 **/
				var str ='<tr><th>包裹号</th><th>收件人地址</th><th>选择</th></tr>';
				var list = data.list;
				for(var i=0;i<list.length;i++){
					var order = list[i];
					var addr = order.dxmPackageAddr;
					if(addr == null){
						addr = "";
					}
					str += '<tr><td style="width:120px;">'+
						'<a href="#">'+order.packageNumber+'</a>'+
						'</td>'+
						'<td style="vertical-align: top;text-align:left;word-break:break-all;word-wrap:break-word;width:420px;">'+
						'<p class="m0">姓名：'+addr.contactPerson+'</p>'+
						'<p class="m0">地址：'+addr.detailAddress+" "+addr.address2+" "+addr.city+" "+addr.province+" "+addr.countryEn+" "+addr.zip+'</p>'+
						'<p class="m0">电话：'+addr.mobile+'</p>'+
						'<p class="m0">手机：'+addr.phoneNumber+'</p>'+
						'</td>'+
						'<td style="width:50px;">'+
						'<input type="radio" name="mergeOrderAddrPackId" value="'+order.id+'" />'+
						'</td>'+
						'</tr>';
				}
				$("#mergeOrderAddrTable").empty();
				$("#mergeOrderAddrTable").html(str);
				$("#mergeOrderPackageId").val(packageIds);
				$("#mergeOrderAddr").modal("show");
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 合并订单地址不同 **/
var mergeOrderAddrDifrent = function(){
	var addrId = $("input[name='mergeOrderAddrPackId']:checked").val();
	if(addrId == undefined || addrId == '' || addrId == 0){
		$.fn.message({type: "error", msg: "请选中地址！"});
		return;
	}
	var packageIds = $("#mergeOrderPackageId").val();
	executeMergeOrder(packageIds, addrId);
	$("#mergeOrderAddr").modal("hide");
};

/** 审核包裹 **/
var auditPackage = function (packageId) {
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/audit.json',
		data: {"packageId": packageId},
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「待处理」页！"});
				$('#packageDetailModal').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			$('#loading').modal('hide');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 批量审核 **/
var batchAuditPackage = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchAudit.json',
		data: ajaxData,
		dataType: "json",
		success: function (data) {
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "订单已移入到「待处理」页！");
			refreshAjaxPage();
			$('#loading').modal('hide');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/* 1000单-批量审核 */
var isOneThousand = false;
var oneThousandOperator = function (val, type, isPrint) {
	var paraData = getOneThousandParaData(true),	// 获取当前提交参数
		url = '',
		successMsg = '',
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if(val == 1){
		// 批量审核
		url = 'package/batchAudit.json';
		successMsg = '订单已移入到「待处理」页！';

	} else if(val == 2){
		// 申请运单号
		url = 'package/batchMoveProcessed.json';
		successMsg = '订单已移入到「运单号申请」页！';

	} else if(val == 3){
		// 移入待打单
		url = 'package/batchMoveAllocated.json';
		successMsg = '订单已移入到「待打单」页！';

	} else if(val == 4){
		// 批量标记面单或拣货单
		if(isNaN(isPrint)) {
			isPrint=1;//默认设置为已打印
		}
		url = 'package/batchSetPrint.json?type='+type+"&isPrint="+isPrint;
		successMsg = '符合条件的订单已标记为' + (isPrint == 0 ? "未打印" : "已打印");

		$("#signedModal").modal("hide");
		$("#printedModal").modal("hide");

	} else if(val == 5){
		// 批量发货
		url = 'package/batchShipGoods.json';
		successMsg = '订单已移入到「已交运」页！';
	}
	if (shopGroupId) paraData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	if (isOneThousand) {
		return;
	}
	if (paraData.oneThousandActionFlag) {
	    if (val == 4) {
            url = url + '&oneThousandActionFlag=' + paraData.oneThousandActionFlag;
        } else {
            url = url + '?oneThousandActionFlag=' + paraData.oneThousandActionFlag;
        }
    }
	isOneThousand = true;
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: url,
		data: paraData,
		dataType: "json",
		success: function (data) {
			if(data.code == -2){
				loadNotice(true, 1);
			} else {
				if(val == 5 && data.code != 0) {
					/*2017.5.17 byzym 添加URL包裹*/
					var msg = strFilterUrl(data.msg);
					$.fn.message({type: "error", msg: msg});
				} else {
					var successList = data.bor.successList;
					var failList = data.bor.failList;
					batchReturnProcess(successList, failList, successMsg);
					refreshAjaxPage();
				}
			}
			$('#loading').modal('hide');
			isOneThousand = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isOneThousand = false;
		}
	});
};

/**(1000单)批量标记打印状态**/
var oneThousandSignPackage = function (type, isPrint) {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	checkSign(packageIds, authId, type, isPrint, 4, 1);
};

/** （1000单）批量发货  **/
var oneThousandBatchShipGoods = function () {

	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if(packageIds == ""){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		return;
	}
	myjAlert.confirm({
		'content':'确定要发货？',
		'callback':function(v){
			if(v){
				oneThousandOperator(5);
			}
		}
	});
};

/** 刷新规则 **/
var isRefreshRule = false;
var refreshRule = function () {
	if(isRefreshRule){
		return;
	}
	isRefreshRule = true;
	var shopId = $("#keepState").data("shopid");
	var platform = $("#keepState").data("platform");
    var allRefresh = $('#paidOrderRefreshRule input:radio[name=refreshPaidLogis]:checked').val();

	var p = 0;		// 记录进度条的值
	$("#refreshOrderRuleModal").modal("show");
	$("#refreshOrderRuleProgressBar").css("width", "0");
	$("#refreshOrderRuleModal_status").html("刷新中...");
	$("#refreshOrderRuleModal_processDetail").html("");
	$.ajax({
		type: "POST",
		url: 'order/refreshRule.json',
		data: {
		    "shopId": shopId,
            "platform": platform,
            "allRefresh" : allRefresh
        },
		dataType: "json",
		success: function (data) {
			var uuid = data.uuid;
			checkProcessStatus(uuid, function(data){
				var num = (parseInt(data.num) / parseInt(data.totalNum)).toFixed(2) * 100;
				var status = "刷新中...";
				if(num < p && data.code != 1){
					// 为了去掉变为n->0时的动画效果，在此先隐藏，然后再置0，最后再定时显示出来
					$("#refreshOrderRuleProgressBar").css("display", "none");
					setTimeout(function(){
						$("#refreshOrderRuleProgressBar").css("display", "");
					},1000);
				}
				p = num;
				if(data.code==0){
					$("#refreshOrderRuleProgressBar").css("width", num + "%");
				}else{
					status = "已完成!";
					$("#refreshOrderRuleProgressBar").css("width", "100%");
					$("#refreshOrderRuleProgressBar").removeClass("active");
				}
				$("#refreshOrderRuleModal_status").html(status);
				$("#refreshOrderRuleModal_processDetail").html(data.msg);
			});
            isRefreshRule = false;
		},
		error: function () {
			$('#loading').modal('hide');
            isRefreshRule = false;
		}
	});
};

/** 关闭流程 **/
var closePaid = function () {
	$("#closePaidModal").modal("show");
};

/** 开启或停用审核流程**/
var updateUserConfig = function (isOpen, val) {
	$.ajax({
		type: "POST",
		url: 'userConfig/update.json',
		data: {"isOpen": isOpen},
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
				$("#paidRemindDiv").css("display", "none");
				if (val == 1) {
					window.location.href = "order/index.htm";
				}
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 搁置订单 **/
var showGezhiDiv = function () {
	$("#gezhi").modal("show");
};

/** 执行搁置订单 **/
var voidedFlag = false;
var setVoided = function () {
	if (voidedFlag) {
		return;
	}
	voidedFlag = true;
	var packageId = $("#detailPackageId").val();
	$.ajax({
		type: "POST",
		url: 'package/setVoided.json',
		data: {"packageId": packageId},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「已搁置」页！"});
				$('#gezhi').modal('hide');
				$('#packageDetailModal').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
				closeDiv('gezhi');
			}
			voidedFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			voidedFlag = false;
		}
	});
};

/** 执行搁置订单 **/
var listVoidedFlag = false;
var setListVoided = function (packageId, free) {
	if (listVoidedFlag) {
		return;
	}
	listVoidedFlag = true;
	$.ajax({
		type: "POST",
		url: 'package/setVoided.json',
		data: {"packageId": packageId},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「已搁置」页！"});
				if(free == 'free'){

				} else {
					refreshAjaxPage();
				}
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			listVoidedFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			listVoidedFlag = false;
		}
	});
};

/** 批量设置搁置 **/
var batchSetVoidedConfirm = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	$("#batchGezhi").modal("show");
};

/** 批量设置搁置 **/
var batchVoidedFlag = false;
var batchSetVoided = function () {
	if (batchVoidedFlag) {
		return;
	}
	batchVoidedFlag = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		batchVoidedFlag = false;
		return;
	}
	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$("#batchGezhi").modal("hide");
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchSetVoided.json',
		data: ajaxData,
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
				var successList = data.bor.successList;
				var failList = data.bor.failList;
				batchReturnProcess(successList, failList, "订单已移入到「已搁置」页！");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			batchVoidedFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			batchVoidedFlag = false;
		}
	});
};

/** 还原搁置订单 **/
var recoveryFlag = false;
var recoveryPackage = function (packageId) {
	if (recoveryFlag) {
		return;
	}
	recoveryFlag = true;
	$.ajax({
		type: "POST",
		url: 'package/recovery.json',
		data: {"packageId": packageId},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: data.msg});
				$('#packageDetailModal').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			recoveryFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			recoveryFlag = false;
		}
	});
};

//移入提交失败
var moveToCommitFailFlag = false;
var moveToCommitFail = function (packageId) {
	if (moveToCommitFailFlag) {
		return;
	}
	moveToCommitFailFlag = true;
	$.ajax({
		type: "POST",
		url: 'package/moveToCommitFail.json',
		data: {"packageId": packageId},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "订单移入【云仓退回-已虚拟发货&拦截成功】"});
				$('#packageDetailModal').modal('hide');
				dxmPackageDetail(packageId);
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			moveToCommitFailFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			moveToCommitFailFlag = false;
		}
	});
};

//还原不再关注的订单
var recoveryIsRemoveFlag = false;
var recoveryIsRemove = function (packageId) {
    if (recoveryIsRemoveFlag) {
        return;
    }
    recoveryIsRemoveFlag = true;
    $.ajax({
        type: "POST",
        url: 'package/recoveryIsRemove.json',
        data: {"packageId": packageId},
        dataType: "json",
        success: function (data) {
            var code = data.code;
            if (code == 0) {
                $.fn.message({type: "success", msg: data.msg});
                $('#packageDetailModal').modal('hide');
                refreshAjaxPage();
            } else {
                $.fn.message({type: "error", msg: data.msg});
            }
            recoveryIsRemoveFlag = false;
        },
        error: function () {
            $('#loading').modal('hide');
            recoveryIsRemoveFlag = false;
        }
    });
};

//批量还原不再关注的订单
var batchRecoveryIsRemoveFlag = false;
var batchRecoveryIsRemove = function () {
	if (batchRecoveryIsRemoveFlag) return;
	batchRecoveryIsRemoveFlag = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId');
	if (!packageIds) {
		$.fn.message({type: 'error', msg: '请至少选择一个订单'});
		batchRecoveryIsRemoveFlag = false;
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: 'POST',
		url: 'package/recoveryIsRemoveBatch.json',
		data: {packageIds: packageIds},
		dataType: 'json',
		success: function (data) {
			var successList = data.bor.successList,
				failList = data.bor.failList;

			batchReturnProcess(successList, failList, '仅显示不再关注记录的订单已还原到相应的状态页');
			refreshAjaxPage();
			$('#loading').modal('hide');
			batchRecoveryIsRemoveFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			batchRecoveryIsRemoveFlag = false;
		}
	});
};

/** 批量恢复订单 **/
var batchRecoveryFlag = false;
var batchRecovery = function () {
	if (batchRecoveryFlag) {
		return;
	}
	batchRecoveryFlag = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		batchRecoveryFlag = false;
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchRecovery.json',
		data: {"packageIds": packageIds},
		dataType: "json",
		success: function (data) {
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "订单已还原到相应的状态页！");
			refreshAjaxPage();
			$('#loading').modal('hide');
			batchRecoveryFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			batchRecoveryFlag = false;
		}
	});
};

/*移除单个已搁置的订单*/
var removePackage = function (packageId) {
	var $dailySaleSetD = $('#dailySaleSetID'),
		dailySale = $dailySaleSetD.attr('data-sale'),
		dailySet = $dailySaleSetD.attr('data-set'),
	    content = '是否不再关注?';


      if(+dailySale === 1 && +dailySet === 1){
		  content = '是否不再关注订单，不再关注后订单将无法移出不再关注';
	  }

	myjAlert.confirm({
		'content': content,
		'callback': function (v) {
			if (v) {
				$('#loading').modal('show');
				$.ajax({
					type: "POST",
					url: 'package/remove.json',
					data: {"packageId": packageId},
					dataType: "json",
					success: function (data) {
						var code = data.code;
						if (code == 0) {
							$.fn.message({type: "success", msg: data.msg});
							$('#packageDetailModal').modal('hide');
							refreshAjaxPage();
						} else {
							$.fn.message({type: "error", msg: data.msg});
						}
					},
					error: function () {
						$('#loading').modal('hide');
					}
				});
			}
		}
	});
};

/*批量移除已搁置的订单*/
var batchRemove = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	myjAlert.confirm({
		'content': '是否不再关注？',
		'callback': function (v) {
			if (v) {
				$('#loading').modal('show');
				$.ajax({
					type: "POST",
					url: 'package/batchRemove.json',
					data: {"packageIds": packageIds},
					dataType: "json",
					success: function (data) {
						var successList = data.bor.successList;
						var failList = data.bor.failList;
						batchReturnProcess(successList, failList, "订单已不再关注！");
						refreshAjaxPage();
						$('#loading').modal('hide');
					},
					error: function () {
						$('#loading').modal('hide');
					}
				});
			}
		}
	});
};

/*批量删除已搁置的手工订单*/
var batchDelectOrder = function () {
	// 判断用户是否已选择订单
	var packageIds = '',
		today = moment().subtract('days', 0).startOf('day').format('YYYY-MM-DD'),
		flagTime = false;
	$('input[name="packageId"]:checked').each(function(){
		var id = $(this).val(),
			createTime = $('#dxmAuthId' + id).attr('data-createtime'),
			formVal = 'packageIds=' + id;
		createTime = moment(createTime).format('YYYY-MM-DD');
		packageIds += packageIds ? '&' + formVal : formVal;
		if (compareDate(today, createTime) > 0) {
			flagTime = true;
			return;
		}
	});
	if (!packageIds) {
		$.fn.message({type: 'error', msg: '请至少选择一个订单'});
		return;
	}
	if (flagTime) {
		$.fn.message({type: 'error', msg: '仅可删除今天创建的手工订单，请重新选择订单'});
		return;
	}
	$('#deleteBatchOrderModal').attr('data-packageIds', packageIds).modal('show');
};
var confirmDelOrder = function () {
	var $deleteBatchOrderModal = $('#deleteBatchOrderModal'),
		packageIds = $deleteBatchOrderModal.attr('data-packageIds');
	$deleteBatchOrderModal.modal('hide');
	MYJ.ajax({
		url: 'package/delHandOrder.json',
		data: packageIds,
		dataType: 'json',
		pointKey: 'delHandOrder',
		success: function (res) {
			if (!res.code) {
				$.fn.message({type: 'success', msg: '删除成功'});
				refreshAjaxPage();
			} else {
				$.fn.message({type: 'error', msg: res.msg});
			}
		}
	});
}

/**批量更换仓库并打回待处理弹层展示**/
var batchUpdateWarenhoseModal = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	$("#orderPackageStockSelects").empty();
	$.ajax({
		type: "GET",
		url: "dxmWarehoseCon/getWarehosesForOrder.json",
		data: {},
		dataType: "json",
		success: function (data) {
			if (data != "") {
				var optionX = "<option value=''>--请选择--</option>";
				$("#orderPackageStockSelects").append($(optionX));
				$.each(data, function (index, value) {
					var optionX = "<option value='" + value.id + "'>" + value.name + "</option>";
					$("#orderPackageStockSelects option").last().after(optionX);
				});
			}
		}
	});
	$('#batchUpdateWarehose').modal("show");
};

// 批量更换仓库弹层展示
var showBatchUpdateWarenhose2Modal = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	$("#warehoseSelects").empty();
	$.ajax({
		type: "GET",
		url: "dxmWarehoseCon/getWarehosesForOrder.json",
		data: {},
		dataType: "json",
		success: function (data) {
			if (data != '') {
				var optionX = '<option value="">--请选择--</option>';
				$.each(data, function (index, value) {
					optionX += '<option value="' + value.id + '">' + value.name + '</option>';
				});
				$('#warehoseSelects').append(optionX);
			}
		}
	});
	$('#batchUpdateWarehose2').modal("show");
};


/**批量修改仓库并打回待处理**/
var isBatchUpdateWarehose = false;
var batchUpdateWarenhose = function () {
	if (isBatchUpdateWarehose) {
		return;
	}
	isBatchUpdateWarehose = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		isBatchUpdateWarehose = false;
		return;
	}
	var storageId = $("#orderPackageStockSelects").val();
	if(storageId == ""){
		$.fn.message({type: "error", msg: "请至少选择一个仓库"});
		isBatchUpdateWarehose = false;
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchUpdateWarenhose.json',
		data: {"packageIds": packageIds,
			"storageId": $("#orderPackageStockSelects").val()
		},
		dataType: "json",
		success: function (data) {
			$("#batchUpdateWarehose").modal("hide");
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "订单已移入到「待处理」页！");
			refreshAjaxPage();
			$('#loading').modal('hide');
			isBatchUpdateWarehose = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isBatchUpdateWarehose = false;
		}
	});
};

/**批量修改仓库**/
var isBatchUpdateWarehose2 = false;
var batchUpdatewarehose2 = function () {
	if (isBatchUpdateWarehose) {
		return;
	}
	isBatchUpdateWarehose2 = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		isBatchUpdateWarehose2 = false;
		return;
	}
	var storageId = $("#warehoseSelects").val();
	if(storageId == ""){
		$.fn.message({type: "error", msg: "请至少选择一个仓库"});
		isBatchUpdateWarehose2 = false;
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchUpdateUnProcessWarehouse.json',
		data: {
			"packageIds": packageIds,
			"storageId": $("#warehoseSelects").val()
		},
		dataType: "json",
		success: function (data) {
			$("#batchUpdateWarehose2").modal("hide");
			if (data.code == 0) {
				var successList = data.data.successList;
				var failList = data.data.failList;
				batchReturnProcess(successList, failList, "更换仓库成功！");
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			refreshAjaxPage();
			$('#loading').modal('hide');
			isBatchUpdateWarehose2 = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isBatchUpdateWarehose2 = false;
		}
	});
};

/** 移入待配货 **/
var isMoveProcessed = false;
var moveProcessed = function (packageId,obj) {
	if (isMoveProcessed) {
		return;
	}
	isMoveProcessed = true;
	if(obj != null && obj != undefined){
		var type = $(obj).closest('.modal-content').find('#updateLogisticsInformation').is(":hidden");
		if(!type){
			$.fn.message({type:'error',msg:'你当前操作尚未保存，请先「保存」后再移入运单号申请'});
			isMoveProcessed = false;
			return;
		}
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/moveProcessed.json',
		data: {
			"packageId": packageId
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「运单号申请」页！"});
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();
			} else if(data.code == -2){
				loadNotice(true, 1);
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			isMoveProcessed = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isMoveProcessed = false;
		}
	});
};

/** 批量移入待配货 **/
var isBatchMoveProcessed = false;
var batchMoveProcessed = function () {
	if (isBatchMoveProcessed) {
		return;
	}
	isBatchMoveProcessed = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		isBatchMoveProcessed = false;
		return;
	}
	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchMoveProcessed.json',
		data: ajaxData,
		dataType: "json",
		success: function (data) {
			if(data.code == -2){
				loadNotice(true, 1);
			} else {
				var successList = data.bor.successList;
				var failList = data.bor.failList;
				batchReturnProcess(successList, failList, "订单已移入到「运单号申请」页！");
				refreshAjaxPage();
			}
			$('#loading').modal('hide');
			isBatchMoveProcessed = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isBatchMoveProcessed = false;
		}
	});
};

/** 移入待打单 **/
var isMoveAllocated = false;
var moveAllocated = function (packageId) {
	if (isMoveAllocated) {
		return;
	}
	isMoveAllocated = true;
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/moveAllocated.json',
		data: {
			"packageId": packageId
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「待打单」页！"});
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			isMoveAllocated = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isMoveAllocated = false;
		}
	});
};

/** 批量移入待打单 **/
var isBatchMoveAllocated = false;
var batchMoveAllocated = function () {
    if (isBatchMoveAllocated) {
        return;
    }
    isBatchMoveAllocated = true;
    // 如果没有选中所有页，要判断用户是否已选择订单
    var packageIds = getCheckBoxValByName("packageId");
    if (packageIds == "") {
        $.fn.message({type: "error", msg: "请至少选择一个订单"});
        isBatchMoveAllocated = false;
        return;
    }

    var fieldType = $("input[name='fieldType']:checked").val();
    if (fieldType == '' || fieldType == undefined) {
        fieldType = 1;
    }
	var ajaxData = {
		packageIds: packageIds,
		fieldType: fieldType
	},
	$shopGroupId = $('#shopGroupId'),
	shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/batchMoveAllocated.json',
        data: ajaxData,
        dataType: "json",
        success: function (data) {
            var successList = data.bor.successList;
            var failList = data.bor.failList;
            batchReturnProcess(successList, failList, "订单已移入到「待打单」页！");
            refreshAjaxPage();
            isBatchMoveAllocated = false;
        },
        error: function () {
            $('#loading').modal('hide');
            isBatchMoveAllocated = false;
        }
    });
};

/** 移入波次 **/
var moveToWave = function (packageId) {
    myjAlert.confirm({
        'content': '确定移入波次？',
        'callback': function (v) {
            if (v) {
                $('#loading').modal('show');
                $.ajax({
                    type: "POST",
                    url: 'package/moveToWave.json',
                    data: {
                        "packageId": packageId
                    },
                    dataType: "json",
                    success: function (data) {
                        $('#loading').modal('hide');
                        if (data.code == 0) {
                            $.fn.message({type: "success", msg: "操作成功，订单已移入到「发货中」页！"});
                            $("#packageDetailModal").modal("hide");
                            refreshAjaxPage();
                        } else {
                            $.fn.message({type: "error", msg: data.msg});
                        }
                    },
                    error: function () {
                        $('#loading').modal('hide');
                    }
                });
            }
        }
    });
};

/** 移入待打单确认框 **/
var batchMoveAllocatedConfirm = function (val) {
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	$.ajax({
		type: "POST",
		url: 'package/isUsedStock.json',
		data: {},
		dataType: "json",
		success: function (data) {
			if (data.code == 1) {
				if(val == 1){
					$("#batchMoveAllocatedConfirmBtn").attr("onclick", "oneThousandOperator(3);");
				} else {
					$("#batchMoveAllocatedConfirmBtn").attr("onclick", "batchMoveAllocated();");
				}
				$("#moveAllocatedConfirmModal").modal("show");
			} else {
				if(val == 1){
					// 一千单打印
					oneThousandOperator(3);
				} else {
					batchMoveAllocated();
				}
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 移入有货 **/
var isLockStock = false;
var lockStock = function (packageId) {
	if (isLockStock) {
		return;
	}
	isLockStock = true;
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/lockStock.json',
		data: {
			"packageId": packageId
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「待打单有货」页！"});
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			isLockStock = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isLockStock = false;
		}
	});
};

/** 刷新库存 **/
var isBatchLockStock = false;
var batchLockStock = function () {
	if (isBatchLockStock) {
		return;
	}
	isBatchLockStock = true;
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchLockStock.json',
		data: {},
		dataType: "json",
		success: function (data) {
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "订单已移入到「待打单有货」页！");
			refreshAjaxPage();
			isBatchLockStock = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isBatchLockStock = false;
		}
	});
};

/** 批量移入有货 **/
var isBatchLockStockIds = false;
var batchLockStockIds = function () {
	if (isBatchLockStockIds) {
		return;
	}
	isBatchLockStockIds = true;
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		isBatchLockStockIds = false;
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchLockStockIds.json',
		data: {"packageIds": packageIds},
		dataType: "json",
		success: function (data) {
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "订单已移入到「待打单有货」页！");
			refreshAjaxPage();
			isBatchLockStockIds = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isBatchLockStockIds = false;
		}
	});
};

/** 移入有货 **/
var isFree = false;
var freeStock = function (packageIds) {
	if (isFree) {
		return;
	}
	isFree = true;
	var ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchFreeStock.json',
		data: ajaxData,
		dataType: "json",
		success: function (data) {
			var failList = data.bor.failList;
			var errMsg = "";
			if(failList.length > 0){
				for (var i = 0; i < failList.length; i++) {
					errMsg = obj.msg;
				}
				$.fn.message({type: "error", msg: errMsg});
			} else {
				$.fn.message({type: "success", msg: "订单已移入到「待打单缺货」页！"});
			}
			refreshAjaxPage();
			isFree = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isFree = false;
		}
	});
};

/** 批量释放库存 **/
var isBatchFreeStock = false;
var batchFreeStock = function () {
	if (isBatchFreeStock) {
		return;
	}
	isBatchFreeStock = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		isBatchFreeStock = false;
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchFreeStock.json',
		data: ajaxData,
		dataType: "json",
		success: function (data) {
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "订单已移入到「待打单缺货」页！");
			refreshAjaxPage();
			isBatchFreeStock = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isBatchFreeStock = false;
		}
	});
};

/** 忽略已发货的提交平台失败 **/
var batIgnoreCommitFail = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchIgnoreCommitFail.json',
		data: {"packageIds": packageIds},
		dataType: "json",
		success: function (data) {
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "错误信息已忽略，已移至「发货成功」！订单实际状态请在平台确认！");
			refreshAjaxPage();
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};



/** 忽略已发货的提交平台失败 **/
var ignoreCommitFail = function (packageIds) {
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'package/batchIgnoreCommitFail.json',
        data: {"packageIds": packageIds},
        dataType: "json",
        success: function (data) {
            $('#loading').modal('hide');

            var successList = data.bor.successList;
            var failList = data.bor.failList;
            if(successList.length > 0){
                $.fn.message({type: "success", msg: "已移至「发货成功」！订单实际状态请在平台确认！"});
                refreshAjaxPage();
            } else {
                var msg = "";
                if (failList.length > 0) {
                    msg = failList[0].msg;
                }
                $.fn.message({type: "error", msg: msg});
            }
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
};

/** 显示处理错误提示框 **/
var showDealShipErrorModal = function(val, packageId, platform){
	$("#dealShipErrorModal").find("input[name='dealError']").prop("checked", false);
	if(val == 0 || val == 1){
		/** 详情页弹框 **/
		$("#changeAgentSpan").text("更换物流");
		$("#dealShipErrSureBtn").attr("onclick", "dealShippedError("+ val +");");
		if(val == 0){
			$("#dealShipErrCancelBtn").attr("onclick", "");
			$("#dealShipErrorCloseBtn").attr("onclick", "");
		} else {
			$("#dealShipErrCancelBtn").attr("onclick", "closeDiv('dealShipErrorModal');");
			$("#dealShipErrorCloseBtn").attr("onclick", "closeDiv('dealShipErrorModal');");
		}
		$("#dealShipErrorPackId").val(packageId);
		$("#dealShipErrorPlatform").val(platform);
	} else if(val == 2){
		/** 批量操作弹框 **/
		$("#changeAgentSpan").text("批量换物流（更换运单号）");
		var packageIds = getCheckBoxValByName("packageId");
		if (packageIds == "") {
			$.fn.message({type: "error", msg: "请至少选择一个订单"});
			return;
		}
		$("#dealShipErrSureBtn").attr("onclick", "batchDealShippedError();");
		$("#dealShipErrCancelBtn").attr("onclick", "");
		$("#dealShipErrorCloseBtn").attr("onclick", "");
	}
	$("#dealShipErrorModal").modal("show");
};

//处理错误不向平台提交警示弹层处理
$(document).off('click', '#dealShipErrorModal input[name="dealError"]')
    .on('click', '#dealShipErrorModal input[name="dealError"]', function(){
        var $that = $(this),
            val = $that.val();

        if(+val === 2){
            $('#confirmOrderStatus').modal('show');
        }
    });

/** 批量处理错误 **/
var batchDealShippedError = function(){
	var val = $("input[name='dealError']:checked").val();
	if (val == "" || val == undefined) {
		$.fn.message({type: "error", msg: "请选择处理操作！"});
		return;
	}
	if(val == 1){
		// 提交平台
		batchIngoreErrCommitPlatform();
	} else if(val == 2) {
		// 忽略错误
		batIgnoreCommitFail();
	} else if(val == 3){
		// 更换物流
		$("#dealShipErrorModal").modal("hide");
		shippedShowBatchProvider(1);
	}
};

/** 物流方式编辑 **/
var editShipInfoCallBack = function(){
	var platform = $("#dealShipErrorPlatform").val();
	editShipInfo(platform);
};

/** 处理错误 **/
var dealShippedError = function(isRefresh){
	var val = $("input[name='dealError']:checked").val();
	if (val === '' || val === undefined) {
		$.fn.message({type: "error", msg: "请选择处理操作！"});
		return;
	}
	var packageId = $("#dealShipErrorPackId").val();
	if(+val === 1){ // 提交平台
		commitPlatform(packageId);
	} else if(+val === 2){// 忽略错误
		ignoreCommitFail(packageId);
	} else if(+val === 3){// 打开详情页，编辑物流方式
		// 先验证是否批量换物流
		$.ajax({
			type: "POST",
			url: 'package/getAddShipped.json',
			data: {"packageId": packageId},
			dataType: "json",
			success: function (data) {
				if(data.isAddShipped == 1){
					$.fn.message({type: "error", msg: "订单选择了批量换号，请在更换物流管理处理订单！"});
				} else if(data.isAddShipped == -1){
					$.fn.message({type: "error", msg: "订单不存在！"});
				} else {
					var platform = $("#dealShipErrorPlatform").val();
					if(isRefresh == 0){
						dxmPackageDetail(packageId, editShipInfoCallBack);
					} else {
						editShipInfo(platform);
					}
				}
			},
			error: function () {
				$('#loading').modal('hide');
			}
		});
	}
};

/** 订单详情
 * shippedId :批量换物流订单id
 * showType ： 0 用于订单 1 用于批量换物流订单
 * **/
var dxmOrderDetail = function (orderId, shippedId,showType,callback) {
	$('#loading').modal('show');

	var history = $("#keepState").data("history");
	if(!history){
		history = "";
	}

	$.ajax({
		type: "POST",
		url: 'order/detail.htm',
		data: {"orderId": orderId, "history":history,"shippedId":shippedId,"showType":showType},
		dataType: "html",
		success: function (data) {
			$('#loading').modal('hide');
			$('#dxmOrderDetailDiv').empty();
			$('#dxmOrderDetailDiv').html(data);
			$('#orderDetails').modal('hide');
			$('#orderDetails').modal('show');
			if (callback != undefined && callback != '') {
				callback();
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 订单占用详情
 * **/
var lockStockInfo = function (packageId) {
	$('#loading').modal('show');

	$.ajax({
		type: "POST",
		url: 'order/lockStockInfo.htm',
		data: {"packageId": packageId},
		dataType: "html",
		success: function (data) {
			$('#loading').modal('hide');
			$('#lockStockModal').empty();
			$('#lockStockModal').html(data);
			$('#lockStockModal').modal('hide');
			$('#lockStockModal').modal('show');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 显示或隐藏弹出层 **/
var detailModalShow = function (val) {
	if (val == 1) {
		// 订单弹层
		$("#orderDetailClose1").attr("onclick", "showMergeSplit(1);");
		$("#orderDetailClose2").attr("onclick", "showMergeSplit(1);");
	} else {
		// 包裹弹出
		$("#packageDetailClose1").attr("onclick", "showMergeSplit(2)");
		$("#packageDetailClose2").attr("onclick", "showMergeSplit(2)");
	}
};

/** 关闭详情页显示合并或拆分弹层 **/
var showMergeSplit = function (val) {
	if (val == 1) {
		$("#splitPackageModal").modal("hide");
		$("#splitPackageModal").modal("show");
	} else if (val == 2) {
		$("#mergePackageModal").modal("hide");
		$("#mergePackageModal").modal("show");
	}
};
var exportPlatformWarehouseShow = function (type) {
	var templateId = $("#exportTemplateSelect").val();
	var arr = '';
	var isMaster= $('#exportModel').find('input[name="isMaster"]:checked ').val();
	if (exportKeys === '') {
		$.fn.message({type: "error", msg: "您没有选择导出任何选项，请选择后再操作!"});
		return;
	}
	if (+templateId === -1 || +templateId === -2) { // 标准模板
		arr = exportDataGetNew('exportModel');
	} else if (templateId > 0) {
		arr = dataGetNew('exportModel'); // 自定义模板
	} else {
		$.fn.message({type: "error", msg: "请选择模板类型!"});
		return;
	}
	var exportKeys = formatFieldFromArrayToString(arr);
	if (!exportKeys) {
		MYJ.message.error('您没有选择导出任何选项，请选择后再操作');
		return;
	}
	var $pageList = $('#pageList'),
		orderIds = [],
		$selIpt = $pageList.find('input[name="productBox"]:checked'),
		url = 'platformWarehouseOrder/exportPlatformOrder.json?exportStyle='+isMaster,
		$keepState = $('#keepState'),

		paramData = {
			ids: '',
			exportKeys: exportKeys,
			actionType: type,
			templateId: templateId,
			shopId: $keepState.data('shopid'),                         //店铺账号
			marketplaceId: $keepState.data('site'),                    //站点
			orderState: $keepState.data('state'),                      //平台状态
			logisticsStatus: $keepState.data('logisticsStatus'),       //物流状态
			country: $keepState.data('country'),                       //国家地区
			searchType: $keepState.data('searchtype'),                 //搜索类型 (orderId订单号，buyerName买家姓名，sku平台sku，contactName收件人,trackNumber跟踪号)
			searchContent: $.trim($('#searchValue').val())/*.replace(/%/g, '\\%').replace(/_/g, '\\_')*/,   //搜索内容
			orderSearchType: $('#productSearchType').val(),     //(0模糊匹配，1精确匹配)
			orderField: $keepState.data('orderfield'),                 //排序字段（order_create_time按下单时间、order_pay_time按付款时间、shipped_time按发货时间、order_amount按订单金额）
			isDesc: $keepState.data('isdesc'),                          //排序方式（0升序，1降序）
			platformOrderType: $('#platformType').val(),                //平台类型
			platform: $('#platform').val(),                              //平台
			orderShippedStartTime: $.trim($('#orderShippedStartTime').val()),                     //高级搜索--发货时间（开始时间）
			orderShippedEndTime: $.trim($('#orderShippedEndTime').val()),                    //高级时间--发货时间（结束时间）
			orderCreateTime: $.trim($('#timeLeft').val()),                     //高级搜索--创建时间（开始时间）
			orderEndTime: $.trim($('#timeRight').val()),                   //高级时间--创建时间（结束时间）
			orderPayStart: $.trim($('#payPlatformTimeLeft').val()),    //高级时间--付款时间（开始时间）
			orderPayEnd: $.trim($('#payPlatformTimeRight').val())//高级时间--付款时间（结束时间）
		};
	if (type === 1) {
		if ($selIpt.length) {
			$selIpt.each(function (i, j) {
				orderIds.push($(j).closest('tr.content').attr('data-orderid'));
			});
			paramData.ids = orderIds.toString();
		} else {
			commonMsgFn('请至少选择一个订单');
			return;
		}
	}
	var $batchCheckReplicaProgressBar = $('#batchCheckReplicaProgressBar'),
		$batchCheckReplicaProcessNum = $('#batchCheckReplicaProcessNum'),
		$reportShow = $('#reportShow'),
		p = 0;
	$('#upDownloadbox').empty();
	$('#batchExportOrderModal').modal('show');
	$batchCheckReplicaProgressBar.css('width', p + '%');
	$batchCheckReplicaProcessNum.text(p);
	$reportShow.empty();
	$('div[uid="downloadFill"]').removeClass('btn-dropdown').find('button[uid="dropdown"]').removeClass('btn-determine').addClass('btn-gray').prop('disabled',true).css('color','#000000');
	commonAjaxFn(url, paramData, 'json', function (res) {
		var uuid = res.uuid;
		checkProcessStatus(uuid, function (data) {
			var num = Math.round(data.num / data.totalNum * 100);
			if (num < p && +data.code !== 1) {
				// 为了去掉变为n->0时的动画效果，在此先隐藏，然后再置0，最后再定时显示出来
				$batchCheckReplicaProgressBar.css('display', 'none');
				setTimeout(function () {
					$batchCheckReplicaProgressBar.css('display', '');
				}, 1000);
			}
			p = num;
			if (+data.code === 0 && (!data.msg || data.msg === 'loading')) {
				$batchCheckReplicaProgressBar.css('width', num + '%');
				$batchCheckReplicaProcessNum.text(data.num);
				$reportShow.text('订单导出数据准备中，请稍等');
			} else if (+data.code === 0 && data.msg === 'run') {
				$batchCheckReplicaProgressBar.css('width', num + '%');
				$batchCheckReplicaProcessNum.text(data.num);
				$reportShow.text('订单正在导出中，请稍后下载...');
			} else if (+data.code === 1 && data.msg === 'stop') {
				$batchCheckReplicaProgressBar.css('width', '100%').removeClass('active');
				$reportShow.text('有新的导出任务，已暂停这个导出任务！').css('color', 'red');
			} else if (data.code === -1) {
				$batchCheckReplicaProgressBar.css('width', '100%');
				$batchCheckReplicaProcessNum.text(data.num);
				$reportShow.text(data.msg).css('color', 'red');
			} else {
				$batchCheckReplicaProgressBar.css('width', '100%').removeClass('active');
				$batchCheckReplicaProcessNum.text(data.totalNum);
				$reportShow.empty().html('导出文件已生成，文件将会在5分钟后失效,请立即下载<br/>');
				if (data.msg) {
					var downUrl = data.msg.split('|'),
						li = '',
						spanStr = '',
						size = 10000,
						start = 1,
						end;
					if (downUrl.length > 1) {
						$.each(downUrl, function (i, val) {
							end = (i === downUrl.length - 1) ? data.totalNum : (start - 1 + size);
							spanStr += '<span class="inline-block" style="width: 33.33%;line-height: 30px;"><a role="menuitem" tabindex="-1" href="' + val + '">下载文件(' + start + '-' + end + ')</a></span>';
							start += size;
						});
						$('#upDownloadbox').html(spanStr);
						$reportShow.html('由于文件过大，已拆分为 ' + downUrl.length + '个文件<br/>');
					} else {
						var msg = data.msg,
							msgOver = getDownloadUrl(msg);

						$('div[uid="downloadFill"]').addClass('btn-dropdown').find('button[uid="dropdown"]').removeClass('btn-gray').addClass('btn-determine').prop('disabled', false).css('color', '#FFFFFF');
						$('.highSpeedDownload').find('a').attr('href', msg);
						$('.standbDownload').find('a').attr('href', msgOver);
					}
				}
			}
		});
	});
};
var commonMsgFn = function (msg, type, isText, time) {
	$.fn.message({type: type ? 'success' : 'error', msg: msg, isText: !!isText, existTime: time ? time : 3000});
};
var commonAjaxFn = function (url, ajaxData, dataType, successCall, errorCall, type, async) {
	var $loading = $('#loading');

	$loading.modal('show');
	$.ajax({
		type: type ? type : 'POST',
		url: gitWinLocHref() + url,
		data: ajaxData,
		dataType: dataType,
		async: !async,
		success: function (data) {
			$loading.modal('hide');
			successCall && typeof successCall === 'function' && successCall(data);
		},
		error: function () {
			$loading.modal('hide');
			if (errorCall && typeof errorCall === 'function') {
				errorCall();
			} else {
				commonMsgFn('网络异常，请稍后重试！');
			}
		}
	});
};

/** 按时间导出订单 **/
var exportOrderExcel = function (obj) {
	var orderTimeBegin = $("#exportTimeBegin").val();
	var orderTimeEnd = $("#exportTimeEnd").val();
	var timeType = $("#exportPaySelect").val();
	var arr = "";
	var templateId = $("#exportTemplateSelect").val();
	var isMaster=$("input[name='isMaster']:checked").val();
	if (+templateId === -1 || +templateId === -2 ) {
		arr = exportDataGetNew('exportModel'); // 标准模板
	} else if (templateId > 0) {
		arr = dataGetNew('exportModel'); // 自定义模板
	} else {
		$.fn.message({type: "error", msg: "请选择模板类型!"});
		return;
	}
	var exportKeys = formatFieldFromArrayToString(arr);
	if (exportKeys == '') {
		$.fn.message({type: "error", msg: "您没有选择导出任何选项，请选择后再操作!"});
		return;
	}
	var state = $("#keepState").data("exportstate");
	if (state == undefined) {
		state = "";
	}
	var history = $("#keepState").data("history");
	if (history == undefined) {
		history = "";
	}
    var ruleId = $("#keepState").data("ruleid");
    if (ruleId == undefined) {
        ruleId = "-1";
    }
    var sysrule = $("#keepState").data("sysrule");
    if (sysrule == undefined) {
        sysrule = "";
    }
	var isVoided = $("#keepState").data("isvoided");
	exportKeys = encodeURIComponent(exportKeys);
	var url = "order/exportPackageOrder.json?orderField=order_pay_time&state=" + state + "&startTime=" + orderTimeBegin + "&endTime=" + orderTimeEnd + "&timeType=" + timeType+"&exportStyle="+isMaster+"&history="+history+"&isVoided="+isVoided+"&ruleId="+ruleId+"&sysrule="+sysrule,
		$shopGroupId = $('#shopGroupId'),
		pageTag = $('#pageTag').val(),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	if (pageTag) url += '&requestLocation=' + pageTag;//如果页面有pageTag内容，则需要传给后端做导出
	$('#exportOrderModel').modal('hide');

	if($('#orderVipLevel').val()>0 && $('#totalNum').val()>3000){
		OrderdailogPic(exportKeys,templateId,url);
	}else {
        confirmModel(exportKeys, templateId, url, "", obj, 1);
	}
};

/** 按时间导出订单 **/
var importOrderExcel = function () {
	var tempVal = $('#importTemplateSelect').val();

	if ('0' === tempVal) {
		$.fn.message({type: 'error', msg: '请选择更换跟踪号的选项后再操作！'});
		return;
	}
	if(!$('#importTrackNumberFileName').text()){
		$.fn.message({type: 'error', msg: '您还没有选中任何文件！'});
		return;
	}
	importTrackNumUp.settings('formData', {'type' : tempVal});
	importTrackNumUp.upload('*');
};

/*2019.1.2 注释掉未使用方法*/
/** 导出包裹 **/
/*var exportPackageExcel = function () {
	var arr = [];							// 数组
	var templateType = $("#keepState").data("templatetype");
	var packageTimeBegin = $("#exportTimeBegin").val();
	var packageTimeEnd = $("#exportTimeEnd").val();

	if (templateType == 'zdy') {
		// 自定义模板
		arr = dataGet('exportModel');
	} else {
		// 标准模板
		arr = exportDataGet('exportModel');
	}
	var packageKeys = formatFieldFromArrayToString(arr);
	if (packageKeys == '') {
		$.fn.message({type: "error", msg: "您没有选择导出任何选项，请选择后再操作!"});
		return;
	}
	var state = $("#keepState").data("exportstate");
	if (state == undefined) {
		state = "";
	}
	var url = "package/exportPackageExcel.htm?packageKeys=" + packageKeys + "&state=" + state + "&packageTimeBegin=" + packageTimeBegin + "&packageTimeEnd=" + packageTimeEnd;
	$('#exportOrderModel').modal('hide');
	window.location.href = url;
};*/
/*2019.1.2 注释掉未使用方法*/

/** 显示批量报关信息 **/
var showBatchCustoms = function () {
	var packageIds = getCheckBoxValByName("packageId"),
	    $batchCustomsInfo = $("#orderbatchCustomsInfo"),
		applyStatus = $("#applyStatus").val(),
        $batchCustomsInfoCon = $("#batchCustomsInfoCon");

	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/showBatchCustoms.htm',
		data: {"packageIds": packageIds},
		dataType: "html",
		success: function (data) {
            $batchCustomsInfoCon.empty();
            $batchCustomsInfoCon.html(data);
			$('#loading').modal('hide');
            $batchCustomsInfo.customModal("hide");
            $batchCustomsInfo.customModal("show");
			if ("fail" == applyStatus) {
				$('#saveAndApplyTrack').addClass('hide');
			} else {
				$('#saveAndApplyTrack').removeClass('hide');
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 验证报关信息 **/
var validateCustom = function (arr, reg, n, msg, errMsg) {
	for (var i = 0; i < arr.length; i++) {
		var val = $.trim($(arr[i]).val());
		if (!val) {
			$.fn.message({type: 'error', msg: msg});
			$(arr[i]).focus();
			return true;
		}
		switch (+n) {
			case 1:
				if (!val.match(reg)) {
					$.fn.message({type: 'error', msg: errMsg});
					$(arr[i]).focus();
					return true;
				}
				break;
			case 2:
				if (reg.test(val)) {
					$.fn.message({type: 'error', msg: errMsg});
					$(arr[i]).focus();
					return true;
				}
				break;
			case 3:
				if (!reg.test(val)) {
					$.fn.message({type: 'error', msg: errMsg});
					$(arr[i]).focus();
					return true;
				}
				break;
			case 4:
				for (var j = 0; j < arr.length; j++) {
					var currentVal = $.trim($(arr[j]).val());
					if ((val === currentVal) && (i !== j)) {
						$.fn.message({type: 'error', msg: msg});
						$(arr[j]).focus();
						return true;
					}
				}
				break;
		}
	}
	return false;
};

/** 批量执行修改报关信息 **/
var batchCustomFlag = false;
var executeBatchCustom = function (saveType) {
	if(batchCustomFlag){
		return;
	}
	batchCustomFlag = true;
	var arr = $("input[name='nameEns']");
	var chArr = $("input[name='nameChs']");
	var enArr = $("input[name='weights']");
	var deArr = $("input[name='declaredValues']");
	var a = validateCustom(arr, /[\u4E00-\u9FA5]/g, 2, "请输入英文报关名", "英文名称不能含有汉字！");
	if (a) {
		batchCustomFlag = false;
		return;
	}
	var b = validateCustom(chArr, "", 0, "请输入中文报关名", "");
	if (b) {
		batchCustomFlag = false;
		return;
	}
	var c = validateCustom(enArr, /^[0-9]*$/, 1, "请输入重量", "申报重量单位为（g）请输入大于等于0的整数");
	if (c) {
		batchCustomFlag = false;
		return;
	}
	var d = validateCustom(deArr, /^\d+(\.\d{1,2})?$/, 3, "请输入价格", "申报金额请输入大于0的数字,小数点保留1-2位");
	if (d) {
		batchCustomFlag = false;
		return;
	}
	var isAllStr = '';
	$("#batchCustomForm").find("input[name='isAddAllCheck']").each(function(){
		var isCheck = '0';
		if($(this).is(":checked")){
			isCheck = '1';
		}
		if(isAllStr == ''){
			isAllStr = isCheck;
		} else {
			isAllStr += ',' + isCheck;
		}
	});
	$("#isBatchCustomsAddAll").val(isAllStr);
    var allBattery = '';			//含电等级
    var $batchBattery = $('input[name="batchBattery"]');
    var $batchBatteryLevel = $('[name="batchBatteryLevel"]');
    for(var i=0;i<$batchBattery.length;i++){
        var battery = 0;
        if($($batchBattery[i]).is(":checked")){
            battery = $batchBatteryLevel[i].value;
        }
        if(allBattery == ''){
            allBattery += battery.toString();
        }else{
            allBattery += "," + battery.toString();
        }
    }
    $("#batchCfBatteryState").val(allBattery);
	var state = $("#keepState").data("state");
	$("#batchCfOrderState").val(state);
	$("#saveType").val(saveType);
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'customsForm/batchUpdate.json',
		data: $("#batchCustomForm").serialize(),
		dataType: "json",
		success: function (data) {
			var successMsg = "";
			if (state == 'approved') {
				if (saveType === 1) {
					successMsg = "物流信息完整的订单已移入到「运单号申请」页！";
				}
			} else if(state == 'processed'){
				successMsg = "点击「重新获取运单号」，再次获取单号";
			}
			$('#batchCustomsInfo').modal('hide');
			batchReturnProcess(data.bor.successList, data.bor.failList, successMsg);
			refreshAjaxPage();
			batchCustomFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			batchCustomFlag = false;
		}
	});
};
/**批量执行修改收件人地址信息*/
var executeBatchAddr = function () {
	var orderIds = $("input[name='orderIds']");
	if(orderIds.length == 0){
		$("#batchPackageAddr").modal("hide");
		refreshAjaxPage();
		return;
	}
	var state = $("#keepState").data("state");
	$("#batchAddrOrderState").val(state);

	var $table = $('#batchPackAddrTable');
	if($table.find('.detailEmailErrorMsg').length) {
		MYJ.message.error('邮箱格式不正确，请检查邮箱');
		return;
	}

	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/batchUpdateContactMsg.json',
		data: $("#batchPackageAddrForm").serialize(),
		dataType: "json",
		success: function (data) {
			$("#batchPackageAddr").modal("hide");
			$('#loading').modal('hide');
			var bor = data.bor,
				failList = bor ? bor.failList : [],
				successList = bor ? bor.successList : [];

			//兼容后端直接在msg里面返回报错的情况
			if (+data.code === -1 && data.msg && bor && !failList.length && !successList.length) {
				MYJ.message.error(data.msg);
			} else {
				batchReturnProcess(data.bor.successList, data.bor.failList, state == 'processed' ? "点击「重新获取运单号」，再次获取单号" : '');
			}
			refreshAjaxPage();
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};
/** 设置时间 **/
var setDays = function (beginDay, endDay, obj) {
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	var begin = dateStr(beginDay);
	var end = dateStr(endDay);
	if (beginDay == -1) {
		begin = "";
		end = "";
	}
	$("#keepState").data("starttime", begin);
	$("#keepState").data("endtime", end);
	setClass(obj);
	packageList();
};

/** 设置自定义时间 **/
var setCustomDays = function () {
	$("#queryCustomsTimeModal").modal("show");
};

/** 自定义时间查询 **/
var queryCustomsDays = function () {

	var beginDay = $("#customsTimeBegin").val();
	var endDay = $("#customsTimeEnd").val();
	if (beginDay == '') {
		$.fn.message({type: "error", msg: "请选择开始时间！"});
		return;
	}
	if (endDay == '') {
		$.fn.message({type: "error", msg: "请选择结束时间！"});
		return;
	}
	var b = compareDate(beginDay, endDay);
	if (b == 1) {
		$.fn.message({type: "error", msg: "结束时间要大于等于开始时间！"});
		return;
	}
    commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
	$("#customsDayBtn").text("自定义（" + beginDay + "~" + endDay + "）");
	$("#queryCustomsTimeModal").modal("hide");
	$("#keepState").data("starttime", beginDay);
	$("#keepState").data("endtime", endDay);
	var obj = $("#customsDayBtn");
	setClass(obj);
	packageList();
};

/** 移除标签 **/
var removeCountryTag = function (id, val, allId, obj) {
	$("#" + id + val).prop("checked", false);
	var b = 0;
	$("#" + id + val).parent().parent().parent().find("input[name='" + id + "']").each(function () {
		if ($(this).prop("checked")) {
			b = 1;
		}
	});
	$(obj).parent().remove();
	if (b == 1) {
		$("#" + id + val).parent().parent().parent().parent().find("input[name='" + allId + "']").prop("checked", true);
	} else {
		$("#" + id + val).parent().parent().parent().parent().find("input[name='" + allId + "']").prop("checked", false);
	}
};
/** 取消全部国家 **/
var removeAllCountryTag = function (all, single) {
	$("input[name='" + all + "']").prop("checked", false);
	$("input[name='" + single + "']").prop("checked", false);
	$("#countryListDiv").empty().append("<div class='clear'></div>");
};

/** 指定国家 **/
var showCountry = function (condVal) {
	var arr = condVal.split(",");
	$("#countryListDiv").empty();
	$("#countryListDiv").append("<div class='clear'></div>");
	$("#queryCountryDiv").find("input[name='queryCountryAll']").prop("checked", false);
	$("#queryCountryDiv").find("input[name='queryCountry']").each(function () {
		$(this).prop("checked", false);
		for (var i = 0; i < arr.length; i++) {
			if (arr[i] == $(this).val()) {
				// 选中
				$(this).prop("checked", true);
				$(this).parent().parent().parent().parent().find("input[name='queryCountryAll']").prop("checked", true);
				var str = addCountryStr($(this).val(), $(this).parent().text());
				$("#countryListDiv .clear").before(str);
			}
		}
	});
	$("#queryCountryModel").modal("show");
};

/** 确定保存国家查询条件 **/
var addQueryCountry = function () {
	var countryStr = getCheckBoxValByName("queryCountry");
	$.ajax({
		type: "POST",
		url: 'queryCondition/update.json',
		data: {"condition": countryStr},
		dataType: "json",
		success: function (data) {
			if (countryStr == '') {
				countryStr = "-1";
			}
			$("#countryOtherBtn").attr("onclick", "setCondition('country','" + countryStr + "',this);");
			$("#queryCountryModel").modal("hide");
			$("#countryOtherBtn").click();
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

//注册方法
$(document).on('click', 'a[uid="hideChange"]', function () {
	var val = $(this).attr('value');
	if (val == 1) {
		$(this).html('显示选项').attr('value', 0);
		$(this).closest('.liDiv').find('ul.noFlaot').hide();
	} else {
		$(this).html('隐藏选项').attr('value', 1);
		$(this).closest('.liDiv').find('ul.noFlaot').show();
	}
});

/********************** 订单列表start *********************/
/** 批量修改物流方式，显示物流选择框 **/
var showBatchProvider = function(){
	var isAll = $('#allPage').is(':checked'),
		orderStatus = $('#orderStatus').val(),
		packageIds = ''; // 如果没有选中所有页，要判断用户是否已选择订单
	if(!isAll){
		packageIds = getCheckBoxValByName('packageId');
		if(!packageIds){
			$.fn.message({type:'error',msg:'请至少选择一个订单'});
			return;
		}
	}
	var $batchProviderSelect = $('#batchProviderSelect');
	if(!$batchProviderSelect.find('option').length){
        getAuthList('batchProviderSelect');
	}else{
        $batchProviderSelect.val('').trigger('chosen:updated');
	}
	$('#batchUpdateProviderBtn0').removeClass('hide');
	if (orderStatus === 'approved') {
		$('#batchUpdateProviderBtn1').removeClass('hide');
	} else if(orderStatus === 'processed'){
		$('#batchUpdateProviderBtn0').addClass('hide');
		$('#batchUpdateProviderBtn1').removeClass('hide');
	} else {
		$('#batchUpdateProviderBtn1').addClass('hide');
	}
	$('#batchUpdateProvider').modal('show');
};

/** 获取物流方式列表 **/
var getAuthList = function(selectId,callBack){
	var code = 0;
	if(selectId === 'batchOneKeySelect'){
		code = 1;
	}else if(selectId === 'shippedBatchProviderSelect'){
		code = 2;
	}
	$.ajax({
		type: 'POST',
		url: 'providerAuth/getList.htm',
		data: {code:code},
		dataType: 'html',
		success: function(data){
			$('#'+selectId).empty().html(data).chosen('destroy').chosen({
                search_contains: true//注册插件
            });
            $('#'+selectId+'_chosen').css('width','250px').find('.chosen-drop').addClass('chosen-drop-oder');
			if(callBack){
				callBack();
			}
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 批量修改物流方式 **/
var batchProviderFlag = false;
var batchUpdateProvider = function(saveType){
	if(batchProviderFlag){
		return;
	}
	batchProviderFlag = true;
	// 所有页是否被选中
	var isAll = $("#allPage").is(':checked');
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = "";
	if(!isAll){
		packageIds = getCheckBoxValByName("packageId");
		if(packageIds == ""){
			$.fn.message({type:"error",msg:"请至少选择一个订单"});
			batchProviderFlag = false;
			return;
		}
		isAll = 0;
	}else{
		isAll = 1;
	}
	var authId = $("#batchProviderSelect").val();
	if(authId == '' || authId == 0){
		$.fn.message({type:"error",msg:"请选择物流方式"});
		batchProviderFlag = false;
		return;
	}
	var state = $("#keepState").data("state");
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/batchUpdateProvider.json',
		data: {"packageIds":packageIds, "isAll":isAll, "authId":authId, "orderState":state, "saveType":saveType},
		dataType: "json",
		success: function(data){
			if(data.code == 0){
				var successList = data.bor.successList;
				var failList 	= data.bor.failList;
				// 提示信息
				var successMsg;
				if (state == 'processed') {
                    successMsg = "点击「重新获取运单号」，再次获取单号";
				} else if (state == 'paid') {
					successMsg = "";
				} else {
					successMsg = "";
					if (saveType === 1) {
						successMsg = "报关信息完整的订单已移入到「运单号申请」页！";
					}
				}
				batchReturnProcess(successList, failList, successMsg);
				$("#batchUpdateProvider").modal("hide");
				refreshAjaxPage();
			}else{
				$.fn.message({type:"error", msg:data.msg});
			}
			batchProviderFlag = false;
		},
		error:function(){
			$('#loading').modal('hide');
			batchProviderFlag = false;
		}
	});
};

/** 批量显示速卖通线上发货订单 **/
var providerChange = function(obj){
	var $option = $(obj).find('option:selected'),
			agentNameType  = $option.attr('agentNameType'),
			authId = $(obj).val(),
		    codType = $option.attr('codType'),
			isBack = $option.attr('isBack'),
			sizeType = $option.attr('sizeType'),
	        agentPackageCountType = $option.attr('agentPackageCountType');
	if(agentNameType == 22 ){
		// 速卖通线上发货
		var authText = $('#batchProviderSelect').find('option[value="'+authId+'"]').text();
		var packageIds = getCheckBoxValByName("packageId");
		if(packageIds == ''){
			$.fn.message({type:"error",msg:"请至少选择一个速卖通订单"});
			return;
		}
		// 检测是否有速卖通订单
		var arr = packageIds.split(",");
		var isSmt = 0;
		for(var i=0;i<arr.length;i++){
			var platform = $("#dxmAuthId"+arr[i]).attr("data-platform");
			if(platform == 'smt'){
				isSmt = 1;
				break;
			}
		}
		$("#batchUpdateProviderBtn0").css("display","none");
		$("#batchUpdateProviderBtn1").css("display","none");
		if(isSmt == 0){
			$.fn.message({type:"error",msg:"仅速卖通订单支持「速卖通线上发货」，请重新选择物流。"});
			return;
		}

		$('#loading').modal('show');
		$.ajax({
			type: "POST",
			url: 'order/showBatchSmtOnline.htm',
			data: {"packageIds":packageIds,"authId":authId},
			dataType: "html",
			success: function(data){
			    var $smtOnLineShip = $('#smtOnLineShip');
				$('#batchUpdateProvider').modal('hide');
                $smtOnLineShip.empty().html(data);
				$('#loading').modal('hide');
                $smtOnLineShip.modal('hide');
                $smtOnLineShip.find("span[data-name='authText']").html('- '+authText);
                $smtOnLineShip.modal('show');
			},
			error:function(){
				$('#loading').modal('hide');
			}
		});

	} else if(agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1 || agentPackageCountType == 1){
		/** postPony物流方式 **/
		postPonyChange(agentNameType, isBack);

	} else if(agentNameType == 353 || agentNameType == 704 || agentNameType == 3 || codType == 1) {
        /** 合联物流方式 **/
		$.ajax({
			type: 'POST',
			url: 'order/getAgentInfo.json',
			data: {
				"authId": $("#batchProviderSelect").val()
			},
			dataType: 'json',
			success: function (data) {
				var apAuth = data.apAuth;
				var agent = data.agent;
				if (agent !== '' && apAuth !== undefined && apAuth !== '' && apAuth !== undefined) {
					if ((agent.agentNameType === 3 && apAuth.isBack === 1) || agent.agentNameType === 353 || (agent.agentNameType === 704 && apAuth.apacPickUpType === 1) || (codType == 1  && apAuth.isBack === 1)) {
						heLianChange();
					}
				}
			},
		});

    }else if(agentNameType == 256 || agentNameType == 419){
		// 中乌速递乌克兰专线
		zwsdChange(agentNameType);

	} else {
		$("#smtOnLineShip").modal("hide");
		$("#batchUpdateProviderBtn0").css("display","");
		$("#batchUpdateProviderBtn1").css("display","");
	}
};

/** 批量显示已发货订单发货信息**/
var shippedProviderChange = function(obj){
	var agentNameType  = $(obj).find("option:selected").attr("agentNameType");
	var authId			= $(obj).val();
	if(agentNameType == 256){
		// 中乌速递乌克兰专线
		var authText = $(obj).find('option[value="'+authId+'"]').text();
		// zwsd物流方式
		var packageIds = getCheckBoxValByName("packageId");
		if(packageIds == ''){
			$.fn.message({type:"error",msg:"请至少选择一个订单"});
			return;
		}
		var orderType = $('#orderTypeHidden').val();
		$("#shippedBatchUpdateBtn").css("display","none");
		$('#loading').modal('show');
		$.ajax({
			type: "POST",
			url: 'order/showBatchZwsd.htm',
			data: {"packageIds":packageIds,"authId":authId,"orderType":orderType},
			dataType: "html",
			success: function(data){
				$("#shippedBatchUpdateProvider").modal("hide");
				if (agentNameType != 419) {
                    $('.kilimallGs').hide();
				}
				$("#zwsdWklShip").empty();
				$("#zwsdWklShip").html(data);
				$('#loading').modal('hide');
				$("#zwsdWklShip").modal("hide");
				$("#zwsdWklShip").find("span[data-name='authText']").html('- '+authText);
				$("#batchUpdateZwsdBtn").data("mode", 1);
				$("#zwsdWklShip").modal("show");
			},
			error:function(){
				$('#loading').modal('hide');
			}
		});
	} else {
		$("#zwsdWklShip").modal("hide");
		$("#shippedBatchUpdateBtn").css("display","");
	}
};

/** 批量修改速卖通线上发货 **/
var batchUpdateSmtOnline = function(type){
	var b = false,
		$smtOnlineForm = $('#smtOnlineForm');

	//验证速卖通是否填写快递单号，先不验证必填了，可在分拨组包时填写
	// $smtOnlineForm.find('input[name="expressTrack"]').each(function(){
	// 	var v = $.trim($(this).val());
	// 	if(v == null || v == ""){
	// 		$(this).focus();
	// 		b = true;
	// 		return false;
	// 	}
	// });
	// if(b){
	// 	$.fn.message({type:"error",msg:"请输入快递单号！"});
	// 	return;
	// }
	$smtOnlineForm.find('select[name="expressId"]').find('option:selected').each(function(){
		if($(this).val() !== '-1'){
			var expressAddr = $(this).text();
			$(this).parent().parent().find('input[name="expressName"]').val(expressAddr);
		} else {
			var expressName = $(this).closest('td').find('input[name="expressName"]').val();
			var expressTrack = $(this).closest('tr').find('input[name="expressTrack"]').val();
			if(!$.trim(expressName) && expressTrack){
				$.fn.message({type: 'error', msg: '请输入国内快递名称！'});
				b = true;
				return false;
			}
		}
	});
	if(b){
		$.fn.message({type: 'error', msg: '请输入国内快递名称！'});
		return;
	}
	var isBatterys = '',
        isLiquids = '';
	$smtOnlineForm.find('input[name="isBattery"]').each(function(){
        isBatterys += (!isBatterys ? '' : ',') + '0';
	});
	$smtOnlineForm.find("input[name='isLiquid']").each(function(){
        isLiquids += (!isLiquids ? '' : ',') + '0';
    });
	$('#smtIsBatterys').val(isBatterys);
	$('#smtIsLiquids').val(isLiquids);
	$('#submitType').val(type);
	$('#loading').modal('show');
	$.ajax({
		type: 'POST',
		url: 'order/batchUpdateSmtOnline.json',
		data: $smtOnlineForm.serialize(),
		dataType: 'json',
		success: function(data){
			$('#loading').modal('hide');
			if(!+data.code){
				var successMsg = '报关信息完整的订单已移入到「运单号申请」页！';
				if(!+type){
                    successMsg = '物流方式保存成功';
				}
				batchReturnProcess(data.bor.successList, data.bor.failList, successMsg);
				$('#smtOnLineShip').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: 'error', msg: data.msg});
				$('#smtOnLineShip').modal('hide').modal('show');
			}
		},
		error:function(){
			$('#loading').modal('hide');
			showNetError();
		}
	});
};

/*** postPony物流start ***/
var postPonyChange = function(agentNameType, isBack){
	var authId			= $("#batchProviderSelect").val();
	// post物流方式
	var packageIds = getCheckBoxValByName("packageId");
	if(packageIds == ''){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		return;
	}
	$("#batchUpdateProviderBtn0").css("display","none");
	$("#batchUpdateProviderBtn1").css("display","none");
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/showBatchPostPony.htm',
		data: {"packageIds":packageIds,"authId":authId,"agentNameType":agentNameType},
		dataType: "html",
		success: function(data){
			$("#batchUpdateProvider").modal("hide");
			$("#postPonyShip").empty().html(data);
			if (+agentNameType === 655 && +isBack === 0) {
				$('.alibabaExpressBox').addClass('hide');
			}
			$('#loading').modal('hide');
			$("#postPonyShip").modal("hide").modal("show");
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 批量修改中乌速递乌克兰专线 **/
var batchUpdateZwsd = function(obj, type){
	var mode = $(obj).data("mode");
	var b = false;
	$("#zwsdWklForm").find("input[name='expressTrack']").each(function(){
		var v = $.trim($(this).val());
		if(v == null || v == ""){
			$(this).focus();
			b = true;
			return false;
		}
	});
	if(b){
		$.fn.message({type:"error",msg:"请输入快递单号！"});
		return;
	}
	if (+type == 1) {
        var flag;
        var reg = /^[0-9]*[1-9][0-9]*$/;
        $("#zwsdWklForm").find("input[name='goodVolume']").each(function(){
            var v = $.trim($(this).val());
            if(v == null || v == "" || !reg.test(v)){
                $(this).focus();
                flag = true;
                return false;
            }
        });
        if(flag){
            $.fn.message({type:"error",msg:"请输入大于0的整数体积！"});
            return;
        }
	}

	$("#zwsdWklForm select[name='expressId']").find("option:selected").each(function(){
		if($(this).val() != "-1"){
			var expressAddr = $(this).text();
			$(this).parent().parent().find("input[name='expressName']").val(expressAddr);
		} else {
			if($(this).val() == "-1"){
				var expressName = $(this).parent().parent().find("input[name='expressName']").val();
				if($.trim(expressName) == ''){
					$.fn.message({type:"error",msg:"请输入国内快递名称！"});
					b = true;
					return false;
				}
			}
		}
	});
	if(b){
		$.fn.message({type:"error",msg:"请输入国内快递名称！"});
		return;
	}
	$('#loading').modal('show');
	if(mode == 0){		// 批量修改中乌速递乌克兰专线物流方式
		$.ajax({
			type: "POST",
			url: 'order/batchUpdateZwsd.json',
			data: $("#zwsdWklForm").serialize(),
			dataType: "json",
			success: function(data){

				$('#loading').modal('hide');
				if(data.code == 0 || data.code == 1){
					var errMsg = data.code == 0 ? '报关信息完整的订单已移入到「运单号申请」页！' : '';
					batchReturnProcess(data.bor.successList, data.bor.failList, errMsg);
					$("#zwsdWklShip").modal("hide");
					refreshAjaxPage();
				} else {
					$.fn.message({type:"error",msg:data.msg});
					$("#zwsdWklShip").modal("hide");
					$("#zwsdWklShip").modal("show");
				}
			},
			error:function(){
				$('#loading').modal('hide');
			}
		});
	}
	if(mode == 1){		// 已发货批量换中乌速递乌克兰专线物流方式
		shippedBatchUpdateForSpecialProvider();
	}
};

/*** 中乌速递乌克兰专线物流start ***/
var zwsdChange = function(agentNameType){
	var authId			= $("#batchProviderSelect").val();
	var authText = $('#batchProviderSelect').find('option[value="'+authId+'"]').text();
	// zwsd物流方式
	var packageIds = getCheckBoxValByName("packageId");
	if(packageIds == ''){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		return;
	}
	$("#batchUpdateProviderBtn0").css("display","none");
	$("#batchUpdateProviderBtn1").css("display","none");
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/showBatchZwsd.htm',
		data: {"packageIds":packageIds,"authId":authId},
		dataType: "html",
		success: function(data){
			$("#batchUpdateProvider").modal("hide");
			$("#zwsdWklShip").empty();
			$("#zwsdWklShip").html(data);
			$('#loading').modal('hide');
			$("#zwsdWklShip").modal("hide");
			$("#zwsdWklShip").find("span[data-name='authText']").html('- '+authText);
			$("#zwsdWklShip").modal("show");
            if (agentNameType != 419) {
                $('.kilimallGs').hide();
            }
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 移除速卖通线上发货 **/
var removeSmtOnline = function(obj){
	$(obj).closest('tr').remove();
};

//批量修改速卖通线上发货验证 长\宽\高\重量 方法
var judgePostPonyFormFn = function ($dom, name, msg, agentPackageCount) {
	var b = false;
	$dom.find('input[name="' + name + '"]').each(function () {
		var v = $.trim($(this).val());
		if (!v) {
			$(this).focus();
			b = true;
			return false;
		}
		if (agentPackageCount == 1 && name == 'agentPackageCount' && (v <= 0 || v > 40)) {
			$(this).focus();
			b = true;
			msg = '包裹数量不得小于等于0或者大于40';
			return false;
		}
	});
	if (b) {
		$.fn.message({type: 'error', msg: msg});
	}
	return b;
};

/** 批量修改速卖通线上发货 **/
var batchUpdatePostPony = function(apacPickUpType, providerType, agentPackageCount){
	var $postPonyForm = $('#postPonyForm')
	if(judgePostPonyFormFn($postPonyForm, 'length', '请输入长度！', agentPackageCount)) return;
	if(judgePostPonyFormFn($postPonyForm, 'width', '请输入宽度！', agentPackageCount)) return;
	if(judgePostPonyFormFn($postPonyForm, 'height', '请输入高度！', agentPackageCount)) return;
	if(judgePostPonyFormFn($postPonyForm, 'weight', '请输入重量！', agentPackageCount)) return;
	if(judgePostPonyFormFn($postPonyForm, 'agentPackageCount', '请输入包裹数量！', agentPackageCount)) return;

	var isHomeAddrs = '';
	$postPonyForm.find('input[name="isHomeAddr"]').each(function () {
		isHomeAddrs += (isHomeAddrs ? ',' : '') + ($(this).prop('checked') ? '1' : '0');
	});
	$('#isHomeAddrs').val(isHomeAddrs);
	MYJ.ajax({
		url: 'order/batchUpdatePostPony.json',
		data: $postPonyForm.serialize() + '&isEditTradePort=' + ($('#isEditTradePort').is(':checked') ? 1 : 0),//是否编辑贸易条款/港口名称,
		success: function (data) {
			if(!+data.code){
				batchReturnProcess(data.bor.successList, data.bor.failList, '报关信息完整的订单已移入到「运单号申请」页！');
				$('#postPonyShip').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: 'error', msg: data.msg});
				$('#postPonyShip').modal('hide').modal('show');
			}
		}
	});
};
/*** postPony物流end   ***/

/** 弹出无打印发货列表  **/
var withOutPrintShipping = function(){
	var state = '<c:out value="${state}"/>';
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if(packageIds == ""){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/withOutPrintShippingList.htm',
		data: {"packageIds":packageIds,"state":state},
		dataType: "html",
		success: function(data){
		    var $modal = $('#withOutPrintShippingModal');

		    $('#loading').modal('hide');
			$('#withOutPrintShippingDiv').html(data);
			//初始化亚马逊配送服务输入框
			DELIVERY_WITHOUT_ORDER.selectAmazonProviders($('#withOutPrintShippingDiv').find('tr[data-platform="amazon"] select[name="providerSel"]'), true);
            $modal.customModal('hide');
            $modal.customModal('show');
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 无打印发货  **/
/*var withOutPrintShip = function(){
	myjAlert.confirm({
		'content':'您确认要发货吗？',
		'callback':function(v){
			if(v){
				var orderArray = [],
					numberArray = [],
					providerArray = [], isShipArray =[], wishCountryArray = [];

				var b = false;
				$("#withOutPrintShippingDiv input[name='tracingNumber']").each(function(){
					var v = $.trim($(this).val());
					if(v == null || v == ""){
						b = true;
						return false;
					}
					numberArray.push(v);
					orderArray.push($(this).data('id'));
				});
				if(b){
					$.fn.message({type:"error", msg:"物流跟踪号不能为空！"});
					return ;
				}

				b = false;
				$("#withOutPrintShippingDiv .providerSel[name='providerSel']").each(function(){
					var v = $.trim($(this).val());
					if(v == null || v == ""){
						b = true;
						return false;
					}
					providerArray.push(v);
				});
				if(b){
					$.fn.message({type:"error", msg:"请选择平台物流承运商！"});
					return ;
				}

				b = false;
				$('#withOutPrintShippingDiv select[name="wishCountrySel"]').each(function () {
					var v = $.trim($(this).val());

					if (!v) {
						b = true;
					}
					wishCountryArray.push(v);
				});

				$("#withOutPrintShippingDiv input[type='radio']:checked").each(function(){
					var val = $(this).val();
					isShipArray.push(val);
				});

				var packageIds = orderArray.join(",");
				var tracingNumbers = numberArray.join(",");
				var providerNames = providerArray.join(",");
				var isShipStr	  = isShipArray.join(",");
				var wishCountrys  = wishCountryArray.join(",");
				$("#withOutPrintShipping").modal('hide');
				$('#loading').modal('show');
				$.ajax({
					type: "POST",
					url: 'package/withOutPrintShip.json',
					data: { "packageIds" : packageIds,
							"tracingNumbers" : tracingNumbers,
							"providerNames" : providerNames,
							"isShipStr" : isShipStr,
							"wishCountrys" : wishCountrys
					},
					dataType: "json",
					success: function(data){
						if(data.code == 0){
							var successList = data.bor.successList;
							var failList 	= data.bor.failList;
							var successMsg  = getSuccessMsg(successList);
							batchReturnProcess(successList, failList,successMsg);
							refreshAjaxPage();
						}else{
							$.fn.message({type:"error", msg:data.msg});
						}
					},
					error:function(){
						$('#loading').modal('hide');
					}
				});
			}
		}
	})
};*/

/** 无打印发货  **/
var withOutPrintShip = function(){
	myjAlert.confirm({
		'content': '您确认要发货吗？',
		'callback': function(v) {
			if (v){
				var $loading = $('#loading'),
					$div = $('#withOutPrintShippingDiv'),
					orderArray = [],
					numberArray = [],
					providerArray = [],
					isShipArray =[],
					wishCountryArray = [],
					b = false;

				//物流跟踪号
				$div.find('input[name="tracingNumber"]').each(function () {
					var v = $.trim($(this).val());

					if (!v) {
						b = true;
						return false;
					}
					numberArray.push(v);
					orderArray.push($(this).data('id'));
				});
				if (b) {
					$.fn.message({type:'error', msg: '物流跟踪号不能为空！'});
					return ;
				}

				b = false;
				//平台物流承运商
				$div.find('.providerSel[name="providerSel"]').each(function () {
					var platform = $(this).closest('tr').attr('data-platform'),
						v = $.trim($(this).val());

					if (!v) {
						b = true;
						return false;
					}
					providerArray.push(v);
				});
				if (b) {
					$.fn.message({type:'error', msg: '请选择平台物流承运商！'});
					return ;
				}


				b = false;
				$div.find('select[name="wishCountrySel"]:visible').each(function () {//wish平台发货地必填
					var v = $.trim($(this).val());

					if (!v) {
						b = true;
						return false;
					}
					wishCountryArray.push(v);
				});
				if (b) {
					$.fn.message({type:'error', msg: '请选择wish发货地！'});
					return ;
				}

				$div.find('input[type="radio"]:checked').each(function () {
					isShipArray.push($(this).val());
				});

				$('#withOutPrintShipping').modal('hide');
				$loading.modal('show');
				$.ajax({
					type: 'POST',
					url: gitWinLocHref() + 'package/withOutPrintShip.json',
					data: {
						packageIds: orderArray.join(','),
						tracingNumbers: numberArray.join(','),
						providerNames: providerArray.join(','),
						isShipStr: isShipArray.join(','),
						wishCountrys: wishCountryArray.join(',')
					},
					dataType: 'json',
					success: function(data){
						$loading.modal('hide');
						if (!+data.code) {
							var successList = data.bor.successList;

							batchReturnProcess(successList, data.bor.failList, getSuccessMsg(successList));
							refreshAjaxPage();
						} else {
							$.fn.message({type:'error', msg: data.msg ? data.msg : '发货失败！'});
						}
					},
					error:function(){
						$loading.modal('hide');
					}
				});
			}
		}
	})
};

/** 改变物流承运商 **/
var changeSelectProvider = function(){
	var authId	   = $("#batchOneKeySelect").val();
	var agentType  = $("#batchOneKeySelect option:selected").attr("agentype");
	var allotType  = $("#batchOneKeySelect option:selected").attr("allotType");
	var agentNameType  = $("#batchOneKeySelect option:selected").attr("agentNameType");

	$("#batchOneKeyTrackNums").val("");
	if(agentType == 2 || agentType == -1 || allotType == 1){
		// 系统对接
		$("#batchOneKeyTrackNumDiv").hide();
	} else {
		$("#batchOneKeyTrackNumDiv").show();
	}
	getAgentPrint(agentNameType,authId);

	var selectNum = $("input[name='packageId']:checked").length;
	$("#selectNum").html(selectNum);
	$("#selectTrackNum").html("0");
};

/** 获取系统对接打印模板类型 **/
var getAgentPrint = function(agentNameType,authId){
	$.ajax({
		type: "POST",
		url: 'providerAuth/getAgentPrint.json',
		data: {"agentNameType":agentNameType,"authId":authId},
		dataType: "json",
		success: function(data){
			var agentPrints = data.agentPrints;
			var agentPrintId 		= data.agentPrintId;
			var printFormat 		= data.printFormat;

			var all = "";
			for(var i=0;i<agentPrints.length;i++){
				if(agentPrintId == agentPrints[i].id){
					all += '<option value='+agentPrints[i].id+' selected>'+agentPrints[i].printName+'</option>';
				} else {
					all += '<option value='+agentPrints[i].id+'>'+agentPrints[i].printName+'</option>';
				}
			}
			if(all == ''){
				if(printFormat == 'A4'){
					all +="<option value='A4' selected>A4</option>";

				} else {
					all +="<option value='A4'>A4</option>";
				}
				if(printFormat == '10X10'){
					all +="<option value='10X10' selected>10X10(热敏)</option>";

				} else {
					all +="<option value='10X10'>10X10(热敏)</option>";
				}
			}
			$("#printFormatSelect").empty();
			$("#printFormatSelect").html(all);
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 回车时间 **/
var keydownEvent = function() {
	var e = window.event || arguments.callee.caller.arguments[0];
	if (e && +e.keyCode === 13) {
		var trackNums = $.trim($('#batchOneKeyTrackNums').val()),					// 物流追踪号集合
			arr = trackNums.split('\n'),
			selectNum = 0;
		for(var i = 0; i < arr.length; i++){
			if(arr[i]){
				selectNum++;
			}
		}
		$('#selectTrackNum').html(selectNum);
	}
};

//常用报关信息搜索
$(document).off('keyup', '.searchOrderBgName').on('keyup', '.searchOrderBgName', function () {
	var $orderBgNameBox = $(this).closest('.orderBgBox').find('.orderBgNameBox'),
		val = $.trim($(this).val()).toLowerCase();

	$orderBgNameBox.closest('div').removeClass('hide');
	if(val){
		$.each($orderBgNameBox, function(i, j){
			if($.trim($(j).text()).toLowerCase().indexOf(val) === -1){
				$(j).closest('div').addClass('hide');
			}
		});
	}
});

var customsObj = '';					// 全部变量编辑报关对象
/** 编辑报关信息 **/
var editCustomsForm = function(productId, orderId, obj, index){
	if (!productId) {
		productId = $(obj).attr('data-proSku');
	}
	confirmUpdateCfOrAddr();
	customsObj = obj;
	// $("#editCustomsFormDiv").show();
	$('.searchOrderBgName').val('');
	$('.orderBgNameBox').closest('div').removeClass('hide');
	$('#customsFormDivBtns').show();
	$('#productId').val(productId);
	$('#customsFormIndex').val(index);
	$('#editCustomsDxmOrderId').val(orderId);
	$('#handCustomsFormLabel').css('display', 'none');
	$('#handCustomsFormSpan').css('display', 'none');

	var $cfObj = $(obj).parent().parent();
	$('#nameEn').val($cfObj.find('.nameEnSpan').text());
	$('#nameCh').val($cfObj.find('.nameChSpan').text());
	$('#declaredValue').val($cfObj.find('.deValSpan').text());
	$('#weight').val($cfObj.find('.weightSpan').text());
	$('#detailHsCode').val($cfObj.find('.hsCodeSpan').text());
	$('#material').val($cfObj.find('.materialSpan').val());
	$('#purpose').val($cfObj.find('.purposeSpan').val());
    var orderBatteryLevel = $cfObj.find('.isBattery').data('battery'),
		orderIsAneroidMarkup = $cfObj.find('.isAneroidMarkup').data('isaneroidmarkup'),
		orderIsSpecialGoods = $cfObj.find('.isSpecialGoods').data('isspecialgoods'),
        $orderIsBattery = $('#orderIsBattery'),
    	$orderBatteryLevel = $('#orderBatteryLevel');

    if(orderBatteryLevel > 0){
        $orderIsBattery.prop('checked', true);
        $orderBatteryLevel.css('display', 'inline-block').find('option[value="' + orderBatteryLevel + '"]').prop('selected', true);
    }else {
        $orderIsBattery.prop('checked', false);
        $orderBatteryLevel.css('display', 'none');
	}
    $('#orderIsAneroidMarkup').prop('checked', +orderIsAneroidMarkup === 1);
    $('#orderIsSpecialGoods').prop('checked', +orderIsSpecialGoods === 1);
	showHideInfo('editCustomsFormDiv', 'customsFormTable');
};

/** 显示报关信息 **/
var showCustomsForm = function(nameCh,nameEn,declaredValue,weight){
	$("#showCustomsFormDiv").css("display","");
	$("#showNameCh").html(nameCh);
	$("#showNameEn").html(nameEn);
	$("#showDeclaredValue").html(declaredValue);
	$("#showWeight").html(weight);
};

/** 默认报关信息 **/
var defaultCustomsForm = function(val, obj, type){
	var $customsForm = $('#customsForm'),
        isAneroidMarkup = $(obj).data('isaneroidmarkup'), //是否含非液体化妆品
		isSpecialGoods = $(obj).data('isspecialgoods');   //是否包含特货 (敏感货)
	if(type === 'edit') {
		if(val == 1){
			$('#nameCh').val($(obj).attr('data-ch'));
			$('#nameEn').val($(obj).attr('data-en'));
			$('#weight').val($(obj).attr('data-weight'));
			$('#detailHsCode').val($(obj).attr('data-hscode'));
			$('#material').val($(obj).attr('data-material'));
			$('#purpose').val($(obj).attr('data-purpose'));
			$('#declaredValue').val($(obj).attr('data-decVal'));
			var battery = $(obj).data('battery');
			if(battery > 0){
				$('#orderIsBattery').prop('checked', true);
				$('#orderBatteryLevel').css('display', 'inline-block')
					.find('option[value="' + battery + '"]').prop('selected', true);
			}else {
				$('#orderIsBattery').prop('checked', false);
				$('#orderBatteryLevel').css('display', 'none');
			}
		} else {
			$('#nameCh').val($customsForm.attr('data-ch'));
			$('#nameEn').val($customsForm.attr('data-en'));
			$('#weight').val($customsForm.attr('data-weight'));
			$('#detailHsCode').val($customsForm.attr('data-hscode'));
			$('#material').val($customsForm.attr('data-material'));
			$('#purpose').val($customsForm.attr('data-purpose'));
			$('#declaredValue').val($customsForm.attr('data-decVal'));
		}
		$('#orderIsAneroidMarkup').prop('checked', +isAneroidMarkup === 1);
		$('#orderIsSpecialGoods').prop('checked', +isSpecialGoods === 1);
	}
	if(type === 'manual') {
		if(val == 1){
			$('.div-dxmSelectionSort').find('#orderCustomsDeclaration span[data-names="nodeName"]').text($(obj).attr('title'));
			$('#packNameCh').val($(obj).attr('data-ch'));
			$('#packNameEn').val($(obj).attr('data-en'));
			$('#packWeight').val($(obj).attr('data-weight'));
			$('#packDetailHsCode').val($(obj).attr('data-hscode'));
			$('#packMaterial').val($(obj).attr('data-material'));
			$('#packPurpose').val($(obj).attr('data-purpose'));
			$('#packDeclaredValue').val($(obj).attr('data-decVal'));
			var battery = $(obj).data('battery');
			if(battery > 0){
				$('#packDetailIsBattery').prop('checked', true);
				$('#batteryLevel').css('display', 'inline-block').removeClass('hide')
					.find('option[value="' + battery + '"]').prop('selected', true);
			}else {
				$('#packDetailIsBattery').prop('checked', false);
				$('#batteryLevel').css('display', 'none');
			}
		} else {
			$('#packNameCh').val($customsForm.attr('data-ch'));
			$('#packNameEn').val($customsForm.attr('data-en'));
			$('#packWeight').val($customsForm.attr('data-weight'));
			$('#packDetailHsCode').val($customsForm.attr('data-hscode'));
			$('#packMaterial').val($customsForm.attr('data-material'));
			$('#packPurpose').val($customsForm.attr('data-purpose'));
			$('#packDeclaredValue').val($customsForm.attr('data-decVal'));
		}
		$('#packDetailIsAneroidMarkup').prop('checked', +isAneroidMarkup === 1);
		$('#packDetailIsSpecialGoods').prop('checked', +isSpecialGoods === 1);
	}
};

/** 取消报关信息 **/
var cancelCustomsForm = function(){
	var packCfUsed = $('#packCfUsed').val();
	if(packCfUsed === 'true'){
		$('#packCustomsFormTable').css('display', '');
		$('#customsFormTable').css('display', 'none');
	} else {
		$('#customsFormTable').css('display', '');
		$('#packCustomsFormTable').css('display', 'none');
	}
	$('#editCustomsFormDiv').hide();
	$('#customsFormDivBtns').hide();
	$('#confirmModal').modal('hide');
	$('#packageDetailModal').modal('hide').modal('show');
	$('#handCustomsFormLabel').css('display', '');
	$('#handCustomsFormSpan').css('display', '');
};

/** 弹出提醒弹窗 **/
var showConfirm = function(){
	var nameCh = $.trim($('#nameCh').val()),
		nameEn = $.trim($('#nameEn').val()),
		weight = $('#weight').val(),
		declaredValue = $('#declaredValue').val(),
		reg = /^[0-9]*$/,
		regVal = /^\d+(\.\d{1,2})?$/;
	// 验证为空
	if(nameCh == null || nameCh.length == 0){
		$.fn.message({type:"error", msg:"报关信息中文名称不能为空!"});
		$("#nameCh").focus();
		return;
	}
	if(nameEn == null || nameEn.length == 0){
		$.fn.message({type:"error", msg:"报关信息英文名称不能为空!"});
		$("#nameEn").focus();
		return;
	}
	if(/[\u4E00-\u9FA5]/g.test(nameEn)){
		$.fn.message({type:"error",msg:"英文名称不能含有汉字！"});
		$("#nameEn").focus();
		return;
	}
	if(!declaredValue.match(regVal) || declaredValue <= 0){
		$.fn.message({type:"error", msg:"申报金额请输入大于0的数字,小数点保留1-2位"});
		$("#declaredValue").focus();
		return;
	}
	if(!reg.test(weight)){
		$.fn.message({type:"error", msg:"申报重量单位为（g）请输入大于等于0的整数"});
		$("#weight").focus();
		return;
	}
	$("#confirmModal").modal("show");
	$("#isAddProduct1").prop('checked', true);
	$("#isAddProduct2").prop('checked', false);
};

/** 重置报关信息 **/
var resetCustomsForm = function(){
	$("#nameCh").val("");
	$("#nameEn").val("");
	$("#weight").val("");
	$("#declaredValue").val("");
};

/*** 执行修改报关信息 ***/
var updateCustomsForm = function(callback){
	var orderId = $.trim($('#editCustomsDxmOrderId').val()),
		nameCh = $.trim($('#nameCh').val()),
		nameEn = $.trim($('#nameEn').val()),
		hsCode = $.trim($('#detailHsCode').val()),
		material = $.trim($('#material').val()),
		purpose = $.trim($('#purpose').val()),
		weight = $.trim($('#weight').val()),
		productId = $.trim($('#productId').val()),
		$parentNode = $(customsObj).parent(),
		sku = $.trim($parentNode.find('.productAttrSku').val()),
		subSku = $.trim($parentNode.find('.productAttr').val()),
		displaySku = $.trim($parentNode.find('.productDisplay').val()),
		declaredValue = $.trim($('#declaredValue').val()),
		isAddProduct  = $.trim($('input[name="isAddProduct"]:checked').val()),		// 是否修改全部
		isBattery = 0,
        isAneroidMarkup = $('#orderIsAneroidMarkup').is(':checked') ? 1 : 0, //smt含非液体化妆品
		isSpecialGoods = $('#orderIsSpecialGoods').is(':checked') ? 1 : 0;	 //smt/wish包含特货 (敏感货)
    if($('#orderIsBattery').is(':checked')){
        isBattery = $.trim($('#orderBatteryLevel').val());
    }

	var reg = /^[0-9]*$/,
		regVal = /^\d+(\.\d{1,2})?$/;
	// 验证为空
	if(!nameCh || !nameCh.length){
		$.fn.message({type: 'error', msg: '报关信息中文名称不能为空！'});
		return;
	}
	if(!nameEn || !nameEn.length){
		$.fn.message({type: 'error', msg: '报关信息英文名称不能为空！'});
		return;
	}
	if(/[\u4E00-\u9FA5]/g.test(nameEn)){
		$.fn.message({type: 'error', msg: '英文名称不能含有汉字！'});
		return;
	}
	if(!declaredValue.match(regVal) || +declaredValue <= 0){
		$.fn.message({type: 'error', msg: '申报金额请输入大于0的数字,小数点保留1-2位'});
		return;
	}
	if(!reg.test(weight)){
		$.fn.message({type: 'error', msg: '申报重量单位为（g）请输入大于等于0的整数'});
		return;
	}

	var obj = $(customsObj).parent().parent(),
		customStr =  /*'tr' + productId + (orderId + 'custom' + $('#customsFormIndex').val())*/null,
		flag = false;

	if ($('td.skuTdNew').length) {
		flag = true;
		$('td.skuTdNew').each(function () {
			var idStr = 'tr' + productId + (orderId + 'custom' + $('#customsFormIndex').val()),
				thisId = $.trim($(this).attr('id'));

			if (thisId && thisId === $.trim(idStr)) {
				customStr = this;
			}
		});
	} else {
		customStr = 'tr' + productId + (orderId + 'custom' + $('#customsFormIndex').val());
	}


	$.ajax({
		type: 'POST',
		url: gitWinLocHref() + 'customsForm/updateCustomForm.json',
		data: {
			orderId: orderId,
			sku: sku,
			subSku: subSku,
			displaySku : displaySku,
			nameCh: nameCh,
			nameEn: nameEn,
			weight: weight,
			declaredValue: declaredValue,
			isAddProduct: isAddProduct,
			material: material,
			purpose: purpose,
			hsCode: hsCode,
			isBattery: isBattery,
			isAneroidMarkup: isAneroidMarkup,
			isSpecialGoods: isSpecialGoods
		},
		dataType: 'json',
		success: function(data){
			var code = 0;
			if(!+code){
				$.fn.message({type: 'success', msg: '保存报关信息成功！'});
				var escapeCodeArr = ['<', '>', '"', "'"]; //只把箭头和单双引号做转义，空格无需转义，且转义空格为nbsp后请求传nbsp给后端会有问题
                nameCh && (nameCh = nameCh.escapeHtml(escapeCodeArr));
                nameEn && (nameEn = nameEn.escapeHtml(escapeCodeArr));
                material && (material = material.escapeHtml(escapeCodeArr));
                purpose && (purpose = purpose.escapeHtml(escapeCodeArr));
                hsCode && (hsCode = hsCode.escapeHtml(escapeCodeArr));
				var count = $(obj).find('.cfProductCount').text(),
					cfStr = '<span class="nameChSpan">' + nameCh + '</span>' + (!nameEn ? '' : '&nbsp;/&nbsp;')
						+ '<span class="nameEnSpan">' + nameEn + '</span>' + (!declaredValue ? '' : '&nbsp;/&nbsp;$')
						+ '<span class="deValSpan">' + declaredValue + '</span>' + (!weight ? '' : '&nbsp;/&nbsp;')
						+ '<span class="weightSpan">' + weight + '</span>'  + (!weight ? '' : '（g）') + (!hsCode ? '' : '&nbsp;/&nbsp;')
						+ '<input class="materialSpan" type="hidden" value="' + material + '"/>'
						+ '<input class="purposeSpan" type="hidden" value="' + purpose + '"/>'
						+ '<span class="hsCodeSpan">' + hsCode + '</span>'
						+ '<span class="cfProductCount" style="display:none;">' + count + '</span>',
					defCustonTr = nameCh + (!nameEn ? '' : '&nbsp;/&nbsp;') +
						nameEn + (!declaredValue ? '' : '&nbsp;/&nbsp;$') +
						declaredValue + (!weight ? '' : '&nbsp;/&nbsp;') +
						weight + (!weight ? '' : '（g）') + (!hsCode ? '' : '&nbsp;/&nbsp;') + hsCode;
                if (+isBattery === 1) {
                    cfStr += '&nbsp;/&nbsp;<span class="isBattery" data-battery="1">含电（内电）</span>';
                    defCustonTr += '&nbsp;/&nbsp;含电（内电）';
                } else if (+isBattery === 2) {
                    cfStr += '&nbsp;/&nbsp;<span class="isBattery" data-battery="2">含电（纯电）</span>';
                    defCustonTr += '&nbsp;/&nbsp;含电（纯电）';
                }
                if(+isAneroidMarkup) {//含非液体化妆品回显
                    cfStr += '&nbsp;/&nbsp;<span class="isAneroidMarkup" data-isaneroidmarkup="1">含非液体化妆品</span>';
                    defCustonTr += '&nbsp;/&nbsp;含非液体化妆品';
				}
                if(+isSpecialGoods) {//特货 (敏感货)回显
                    cfStr += '&nbsp;/&nbsp;<span class="isSpecialGoods" data-isspecialgoods="1">特货 (敏感货)</span>';
                    defCustonTr += '&nbsp;/&nbsp;特货 (敏感货)';
				}
				$(obj).find('.tdCustomsForm').html(cfStr);
				$(flag ? customStr : '#' + customStr).html(defCustonTr);
				$('#customsInformationSpan').removeClass('glyphicon-remove fRed').addClass('glyphicon-ok fGreen');
				cancelCustomsForm();
				if(typeof callback === 'function'){
					callback();
				}
				// 设置报关总额
				allCustomsForm();
			} else {
				$.fn.message({type: 'error', msg: data.msg});
			}
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 重置收货地址 **/
var resetAddress = function(){
	$("#detailZip").val("");			// 邮编
	$("#detailPhone").val("");			// 电话
	$("#detailCountry").val('').trigger("chosen:updated");		// 国家
	$("#detailProvince").val("");		// 州,省份
	$("#detailCity").val("");			// 城市
	$("#detailContact").val("");		// 联系人
	$("#detailMobile").val("");			// 手机
	$("#detailAddress1").val("");		// 详细地址
	$("#detailAddress2").val("");		// 地址2
	$("#companyName").val("");		// 公司
	$("#taxNumber").val("");		// 税号
	$("#apartmentNumber").val("");		// 门牌号

};

/** 标签切换信息 **/
var tabShowInfo = function(val){
	$("#updateAddressDiv").hide();
	$("#editCustomsFormDiv").hide();
	$("#customsFormDivBtns").hide();
	$("#updateLogisticsInformation").hide();
	$("#reApplayTrackBtn").addClass('hide');
	if(val == 1){
		// 收货地址
		$("#deliveryAddress").css("display","");

	} else if(val == 2){
		// 报关信息
		var packCfUsed = $("#packCfUsed").val();
		if(packCfUsed == 'true'){
			$("#packCustomsFormTable").css("display","");
			$("#customsFormTable").css("display","none");
		} else {
			$("#customsFormTable").css("display","");
			$("#packCustomsFormTable").css("display","none");
		}
	} else if(val == 3){
		// 物流信息
		$("#logisticsInformation").css("display","");
	}
};

/** 显示隐藏信息 **/
var showHideInfo = function(showId, hideId){
	$('#detailCountry').val($('#detailAddressCountry1').val());
	$('#' + hideId).hide();
	var stoTime = setTimeout(function () { //加个延时，避免显示太快造成报关信息的常用报关信息掉下来
        $('#' + showId).css('display', '');
        clearTimeout(stoTime);
    }, 10);
	if(showId === 'updateAddressDiv'){
		confirmUpdateCfOrAddr();
	}else if(showId === 'updateLogisticsInformation'){
		var $updateLogisticsInformation = $('#updateLogisticsInformation');
		if(+$updateLogisticsInformation.data('type')){
			/*搜索插件调用 start*/
			$('.chosen-select-fixed').chosen();
			$('#detailCountry_chosen').css('width', '170px').find('span').html($('#detailCountry1').attr('name11'));
			$('#wishCountry_chosen').addClass('m-right10').css('width', '120px').find('.chosen-drop').addClass('chosen-drop-country');
			$('#walmartCountryCode_chosen').addClass('m-right10').css('width', '120px').find('.chosen-drop').addClass('chosen-drop-country');
			$('#updateShipInfoAuthSelect1_chosen,#updateShipInfoAuthSelect_chosen').addClass('m-right10').css('width', '200px').find('.chosen-drop').addClass('chosen-drop-oder');
			$('.chosen-search').find('input').attr('placeholder', '支持中文、英文、二字码搜索');
			$('.chosen-single').css({'height': '33px', 'line-height': '33px'}).find('div').css('top', '4px');

			$.each($('select'),function (i,j) {
				if($(j).hasClass('hide')){
					$('#' + $(j).attr('id') + '_chosen').addClass('hide');
				}
			});
			/*end*/
			$updateLogisticsInformation.data('type', 0);
		}
	}
};

/** 取消修改收货地址 **/
var cancelUpdateAddr = function(){
	var smtAdrHasReview = $('#smtAdrHasReview').val();
	if(smtAdrHasReview === 'false'){
		$("#detailContact").val( $("#detailContact1").text() );				// 联系人
		$("#detailPhone").val( $("#detailPhone1").text() );					// 电话
		$("#detailMobile").val( $("#detailMobile1").text() );				// 手机
		$("#detailAddress1").val( $("#detailAddr11").text() );				// 详细地址
		$("#detailAddress2").val( $("#detailAddress21").text() );			// 地址2
	}
	$("#detailZip").val( $("#detailZip1").text() );						// 邮编
	$("#detailCountry").val( $("#detailAddressCountry1").val()).trigger("chosen:updated");		// 国家
	$("#detailProvince").val( $("#detailProvince1").text() );			// 州,省份
	$("#detailCity").val( $("#detailCity1").text() );					// 城市
	$("#companyName").val( $("#companyName1").text() );					// 公司名
	$("#apartmentNumber").val( $("#apartmentNumber1").text() );			// 门牌号
	$("#taxNumber").val( $("#taxNumber1").text() );						// 税号

	showHideInfo("deliveryAddress","updateAddressDiv");
};

/*** 执行修改收货人地址 ***/
var updateAddress = function(callback){
	var $smtAdrHasReview = $('#smtAdrHasReview');
	var packageId  = $("#detailPackageId").val();			// 包裹ID
	var zip 		= $.trim($('#detailZip').val());			// 邮编
	var phone 		= $.trim($('#detailPhone').val());		// 电话
	var country 	= $("#detailCountry").val();			// 国家
	var province	= $("#detailProvince").val();			// 州,省份
	var city 		= $("#detailCity").val();				// 城市
	var contact 	= $("#detailContact").val();			// 联系人
	var mobile 		= $("#detailMobile").val();				// 手机
	var detailAddr  = $("#detailAddress1").val();			// 详细地址
	var address2 	= $("#detailAddress2").val();			// 地址2
	var companyName = $("#companyName").val();				// 公司名
	var apartmentNumber = $("#apartmentNumber").val();		// 门牌号
	var taxNumber = $("#taxNumber").val(); 					// 税号
	var countryStr = $("#detailCountry option:selected").text();	// 国家显示值

	$.ajax({
		type: "POST",
		url: 'dxmPackageAddr/update.json',
		data: {
			"packageId":packageId,
			"zip":zip,
			"phone":phone,
			"country":country,
			"province":province,
			"city":city,
			"contact":contact,
			"mobile":mobile,
			"detailAddr":detailAddr,
			"address2":address2,
			'companyName' : companyName,
			'apartmentNumber' : apartmentNumber,
			'taxNumber' : taxNumber
		},
		dataType: "json",
		success: function(data){
			var code = data.code;
			if(code == 0){
				$.fn.message({type:"success", msg:"保存收货地址成功!"});
				$("#addressSpan").removeClass("glyphicon-remove fRed").addClass("glyphicon-ok fGreen");
				$("#detailZip1").text(zip);					// 邮编
				$("#detailPhone1").text(phone);				// 电话
				$("#detailCountry1").text(countryStr);		// 国家
				$("#detailProvince1").text(province);		// 州,省份
				$("#detailCity1").text(city);				// 城市
				$("#detailContact1").text(contact);			// 联系人
				$("#detailMobile1").text(mobile);			// 手机
				$("#detailAddr11").text(detailAddr);		// 详细地址
				$("#detailAddress21").text(address2);		// 地址2
				$("#companyName1").text(companyName);		// 公司名
				$("#apartmentNumber1").text(apartmentNumber);// 门牌号
				$("#taxNumber1").text(taxNumber);		// 税号

				$("#detailAddressCountry1").val(country);

				/* 如果是smt订单而且有加密字段的，在更改完信息后，把查看信息按钮移除 */
				if($smtAdrHasReview.val() === 'true'){
					$smtAdrHasReview.val('false');
					$('#showSmtAdrInfo').remove();
				}

				cancelUpdateAddr();

				if(callback != undefined && callback != ''){
					callback();
				}
			} else {
				$.fn.message({type:"error", msg:data.msg});
			}
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 编辑物流方式 **/
var editShipInfo = function(platform){
	$('#isEditState').val('edit');
	showHideInfo('updateLogisticsInformation', 'logisticsInformation');

	var authId = $('#detailPackageAuthId').val(),
		agentProvider = $('#detailPackageAgentProvider').val(),
		trackNum = $('#detailPackageTrackNum').val(),
        isBehind = $('#detailPackageIsBehind').val(),
        fcode = $('#detailPackageFcode').val(),
		$shipInfoSel = $('#updateShipInfoAuthSelect'),
        $trackingNumber = $('#trackingNumber'),
        $reApplayTrackBtn = $('#reApplayTrackBtn'),
		$trackingNumberBox = $('#trackingNumberBox');
	var showCodAmount = +$shipInfoSel.find('option:selected').attr('isBack');
	var apacPickUpType = +$shipInfoSel.find('option:selected').attr('apacPickUpType');
	var codType = +$shipInfoSel.find('option:selected').attr('codtype');
	var sizeType = +$shipInfoSel.find('option:selected').attr('sizetype');
	var agentPackageCountType = +$shipInfoSel.find('option:selected').attr('agentPackageCountType');

	if(authId > 0){
		$shipInfoSel.val(authId);
		$(".chosen-select-fixed").trigger('chosen:updated');

		var agentType = $('#agentType').val(),
			allotType = $('#allotType').val();

		// 系统对接或号码池分配
		if(+agentType === 2 || +agentType === -1 || +allotType === 1) $reApplayTrackBtn.removeClass('hide');

		var packageState = $('#detailPackageState').val();
		if((+agentType === 2 || +agentType === -1) && (packageState === 'virtualShipped' || packageState === 'shipped')){
            $reApplayTrackBtn.attr('onclick', 'showGeneratePackNum();');
		} else {
			var packageId = $('#detailPackageId').val();
            $reApplayTrackBtn.attr('onclick', "reApplyTrackNum('"+packageId+"', 0);");
		}

		var agentNameType = $('#agentNameType').val(),
				$inlandExpressCodeBox = $('div.inlandExpressCodeBox');

		$inlandExpressCodeBox.addClass('hide');
		if(+agentNameType === 105 || +agentNameType === 655 || +agentNameType == 448 || +agentNameType == 734 || +sizeType == 1){ // postPony物流
			if(agentNameType == 655 || agentNameType == 448 || agentNameType == 734){
				$("[name='alibabaOnlineDisplay']").css("display", "none");
				if(agentNameType == 655){
					var isBack = +$shipInfoSel.find('option:selected').attr('isBack') === 0;
					$inlandExpressCodeBox[isBack ? 'addClass' : 'removeClass']("hide");
				}
			}
			$('#postPonyExpressDiv').css('display', '');
			if (agentNameType == 105) {
				$("[name='alibabaOnlineDisplay']").css("display", "");
			}
		} else {
			$('#postPonyExpressDiv').css('display', 'none');
		}

		if (agentPackageCountType == 1) {
			$("[name='agentPackageCountDisplay']").css("display", "");
		} else {
			$("[name='agentPackageCountDisplay']").css("display", "none");
		}

		if(+agentNameType === 256 || +agentNameType === 419){ // 中乌速递乌克兰专线或kilimall线上发货
			expressAjax();
			// 回显
			$('#zwsdExpressTrackNumber').val($('#inlandExpressNumberHidden').val());
			if (+agentNameType === 419) {
                $('#zwsdExpressTrackNumber').attr('placeholder', '请输入跟踪号(多个用逗号隔开)');
                $('#goodVolume').val($('#expressVolumeHidden').val() );
                $('#goodPack').val($('#expressPackHidden').val());
                $('#expressPackHidden').val() == 1 ? $('#goodPack').prop('checked', true) : $('#goodPack').prop('checked', false);
            } else {
                $('.kilimallContent').css('display', 'none');
			}
			$('#zwsdWklExpressDiv').css('display', '');
		} else {
			$('#zwsdWklExpressDiv').css('display', 'none');
		}
		if(+agentNameType === 353 || (agentNameType == 704 && apacPickUpType == 1) || (agentNameType == 3 && showCodAmount == 1) || (codType == 1 && showCodAmount == 1)) {	// 合联物流、华灵云、出口易显示COD
			$('#heLianExpressCodAmount').val($('#heLianCodAmountHidden').val());
			$('#heLianExpressDiv').css('display', '');
		} else {
			$('#heLianExpressDiv').css('display', 'none');
		}

	} else {
		if(agentProvider === '' || agentProvider == null) agentProvider = 0;
		$shipInfoSel.val(agentProvider);
	}
	//$shipInfoSel.trigger('chosen:updated');
	removeDisabled($trackingNumber.val(trackNum));
	if(platform === 'smt') {
		setSmtInfo();
	} else if(platform === 'walmart') {
		var $walmartCountryCodeChosen = $('#walmartCountryCode_chosen');
		if ($(':radio[name="agentRadio"]:checked').val() === '1'){
			$walmartCountryCodeChosen.addClass('hide');
		} else {
			$walmartCountryCodeChosen.removeClass('hide');
		}
	}

	//判断当前编辑的订单物流信息是存在物流商单号还是跟踪单号，物流商单号为ture
	if(behindTrackNumberType){
        $trackingNumberBox.removeClass('hide').css('display','').find('div').empty().html(forwardOrderNumberId);
        $reApplayTrackBtn.addClass('hide');
        $trackingNumber.addClass('hide');
	}else{
        $trackingNumberBox.addClass('hide');
        $reApplayTrackBtn.removeClass('hide');
        $trackingNumber.removeClass('hide');
	}
};

/** 取消物流信息 **/
var cancelShipInfo = function(){
	$('#isEditState').val('save');
	var agentType = $("#agentType").val();					// 物流承运商类型
	var allotType = $("#allotType").val();					// 分配方式
	var trackNum  = $("#detailPackageTrackNum").val();		// 物流追踪号

	if((trackNum == null || trackNum == "") && (agentType == 2 || agentType == -1 || allotType == 1)){
		$("#reApplyTrackNumBtn").removeClass('hide');
	} else {
		$("#reApplyTrackNumBtn").addClass('hide');
	}
	if(agentType != 2 && agentType != -1 && allotType == 0){
		// 手动上传
		$("#trackNumLabel").html("手动上传");
	} else if(allotType == 1){
		// 号码池分配
		//$("#trackNumLabel").html("号码池分配");
		$("#trackNumLabel").html("自动获取");
	} else if(agentType == 2 || agentType == -1){
		// 自动分配
		$("#trackNumLabel").html("自动获取");
	}
	showHideInfo("logisticsInformation","updateLogisticsInformation");
};

/** 获取单号方式 **/
var agentRadioSelect = function(val){
	var $reApplayTrackBtn = $('#reApplayTrackBtn'),
		$updateShipInfoAuthSelectChosen = $('#updateShipInfoAuthSelect_chosen'),
		$updateShipInfoAuthSelect1Chosen = $('#updateShipInfoAuthSelect1_chosen'),
		$wishCountryChosen = $('#wishCountry_chosen'),
		$walmartCountryCodeChosen = $('#walmartCountryCode_chosen');

	if(+val === 0){
		$updateShipInfoAuthSelectChosen.addClass('hide');
		$updateShipInfoAuthSelect1Chosen.removeClass('hide');
		$wishCountryChosen.removeClass('hide');
		$walmartCountryCodeChosen.removeClass('hide');
		if($reApplayTrackBtn) {
			$reApplayTrackBtn.addClass('hide');
		}
		$('#gotoLogistics').addClass('myj-hide');
	} else {
		$updateShipInfoAuthSelectChosen.removeClass('hide');
		$updateShipInfoAuthSelect1Chosen.addClass('hide');
		$wishCountryChosen.addClass('hide');
		$walmartCountryCodeChosen.addClass('hide');
		if($reApplayTrackBtn) {
			$reApplayTrackBtn.removeClass('hide');
		}
	}
	// 切换获取方式的时候 去除快递单号报错
	$('#expressTrackNum').removeClass('border-red').closest('td').find('.trackNumErrorMsg').remove();
};

//更换运单号弹层跟踪单号输入框事件
var removeDisabled = function(obj){
	var val = $.trim($(obj).val());
	//如果跟踪单号输入框为空，则把保存按钮的样式修改为灰色
	$('.updateOrderNumberSubmitBtn').addClass(val ? 'btn-determine' : 'btn-gray').removeClass(val ? 'btn-gray' : 'btn-determine');
};

//修改物流信息时改变物流方式，物流追踪号置为空
var selectProvider = function(val/*, flag*/){
	//选择是平台渠道，则去掉齿轮,其他的则加齿轮，2018/4/19
    var $updateShipInfoAuthSelect = $('#updateShipInfoAuthSelect'),
		$reApplayTrackBtn = $('#reApplayTrackBtn'),
		$trackingNumber = $('#trackingNumber'),
		$trackNumLabel = $('#trackNumLabel'),
		reg = /^[1-9]+[0-9]*$/,
		updateShipInfoAuthSelect = $updateShipInfoAuthSelect.val(); // 当前选中的值

	var $updateShipInfoAuthSelectOpt = $updateShipInfoAuthSelect.find('option:selected'),
		agentType  = $updateShipInfoAuthSelectOpt.attr('agentype'),
		allotType  = $updateShipInfoAuthSelectOpt.attr('allotType'),
		agentNameType = $updateShipInfoAuthSelectOpt.attr('agentNameType'),
			isBack = $updateShipInfoAuthSelectOpt.attr('isBack'),
    	agentRadio = $("input[name='agentRadio']:checked").val(),						// 获取单号方式
	    codType = $updateShipInfoAuthSelectOpt.attr('codType'),
	    sizeType = $updateShipInfoAuthSelectOpt.attr('sizeType');
	var apacPickUpType = $updateShipInfoAuthSelectOpt.attr('apacPickUpType');			// 揽收类型
	var agentPackageCountType = $updateShipInfoAuthSelectOpt.attr('agentPackageCountType');			// 揽收类型
	var agentWeightType = $updateShipInfoAuthSelectOpt.attr('agentWeightType');			// 揽收类型
	var agentDefaultSizeType = $updateShipInfoAuthSelectOpt.attr('agentDefaultSizeType');			// 揽收类型

	if (reg.test(updateShipInfoAuthSelect) && agentRadio == 1) {
		$('#gotoLogistics').removeClass('myj-hide');
	} else {
		$('#gotoLogistics').addClass('myj-hide');
	}

    if(agentRadio == 0 || (agentRadio == undefined && val == 0 && allotType == undefined)){
        $('#wishCountry_chosen').removeClass('hide');
    } else {
        $('#wishCountry_chosen').addClass('hide');
    }
	removeDisabled($trackingNumber.val(''));
	var trackNum  = $('#detailPackageTrackNum').val(),				// 物流追踪号
		authId = $('#detailPackageAuthId').val(),				// 物流方式ID
		agentProvider = $('#detailPackageAgentProvider').val();		// 平台物流方式

	if(authId == 0 && updateShipInfoAuthSelect == agentProvider){
		removeDisabled($trackingNumber.val(trackNum));

	} else if(authId > 0 && updateShipInfoAuthSelect == authId){
		removeDisabled($trackingNumber.val(trackNum));
	}
	var packageId = $('#detailPackageId').val();
	if(agentType == 2 || agentType == -1){
		// 系统对接
        $trackNumLabel.html('自动获取');
        $reApplayTrackBtn.removeClass('hide');
		if(val == 0){
			// 重新生成包裹号
            $reApplayTrackBtn.attr('onclick',"reApplyShipTrackNum('"+packageId+"');");
		} else {
			var packageState = $('#detailPackageState').val();
			if(packageState === 'virtualShipped' || packageState === 'shipped'){
                $reApplayTrackBtn.attr('onclick','showGeneratePackNum();');
			} else {
                $reApplayTrackBtn.attr('onclick',"reApplyTrackNum('"+packageId+"',0);");
			}
		}
	} else {
		if(val == 0){
			// 重新生成包裹号
            $reApplayTrackBtn.attr('onclick',"reApplyShipTrackNum('"+packageId+"');");
		} else {
            $reApplayTrackBtn.attr('onclick',"reApplyTrackNum('"+packageId+"',0);");
		}
		if(allotType == 1){
            $trackNumLabel.html('自动获取');
            $reApplayTrackBtn.removeClass('hide');

		} else if(allotType == 0) {
            $trackNumLabel.html('手动上传');
            $reApplayTrackBtn.addClass('hide');
		} else {
            $trackNumLabel.html('无');
            $reApplayTrackBtn.addClass('hide');
			if(val == 0){
				$('#wishCountry_chosen').removeClass('hide');
			}
		}
	}

	var $inlandExpressCodeBox = $('div.inlandExpressCodeBox');
	$inlandExpressCodeBox.addClass('hide');
	if(agentNameType == 22){
		// 显示速卖通物流承运商设置
		$('#smtExpressDiv').css('display','');
		var $smtExpressName = $('#smtExpressDiv').find('.smtExpressName');
		if($smtExpressName) $smtExpressName.css('display', 'none');
		$('#postPonyExpressDiv').css('display', 'none');
		$('#zwsdWklExpressDiv').css('display', 'none');
        $('#heLianExpressDiv').css('display', 'none');
		setSmtOnline();
		// 切换物流方式的时候 去除快递单号报错
		$('#expressTrackNum').removeClass('border-red').closest('td').find('.trackNumErrorMsg').remove();
	} else if(agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1){
		if(agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1){
			$("[name='alibabaOnlineDisplay']").css("display", "none");
			if(agentNameType == 655){
				$inlandExpressCodeBox[+isBack === 0 ? 'addClass' : 'removeClass']('hide');
			}
		}
		if (agentNameType == 105) {
			$("[name='alibabaOnlineDisplay']").css("display", "");
		}
		// postPony物流
		$('#smtExpressDiv').css('display','none');
		$('#zwsdWklExpressDiv').css('display','none');
		if (codType == 1 && isBack == 1) {
			$('#heLianExpressDiv').css('display', '');
		} else {
			$('#heLianExpressDiv').css('display', 'none');
		}
		/*if (!flag || (flag && +agentNameType === 448)) */$('#postPonyExpressDiv').css('display', '');
		if (sizeType == 1) {
			$("[name='lengthUnitIn']").remove();
		} else {
			$("[name='lengthUnitIn']").css("display", "");
			var inValue = $("#lengthUnit option[value='in']").val();
			if (inValue == null || inValue == undefined || inValue == '') {
				var optionLengthUnitIn = "<option value='in'>in</option>";
				$("#lengthUnit").prepend(optionLengthUnitIn);
			}
		}

		if (agentWeightType == 1 || agentNameType == 105) {
			$("[data-name='agentWeightDisplay']").css("display", "");
			if (agentWeightType == 1) {
				$("#weightUnit option[value='oz']").remove();
			} else {
				$("#weightUnit option[value='oz']").css("display", "");
				var oz = $("#weightUnit option[value='oz']").val();
				if (oz == null || oz == undefined || oz == '') {
					var optionWeightUnit = "<option value='oz'>盎司</option>";
					$("#weightUnit").prepend(optionWeightUnit);
				}
			}
		} else {
			$("[data-name='agentWeightDisplay']").css("display", "none");
			var oz = $("#weightUnit option[value='oz']").val();
			if (oz == null || oz == undefined || oz == '') {
				var optionWeightUnit = "<option value='oz'>盎司</option>";
				$("#weightUnit").prepend(optionWeightUnit);
			}
		}

		if (agentNameType == 734 || agentNameType == 842 || agentNameType == 859 || agentDefaultSizeType == 1) {
			$('#postLength').val(1);
			$('#postWidth').val(1);
			$('#postHeight').val(1);
		} else {
			$('#postLength').val(0);
			$('#postWidth').val(0);
			$('#postHeight').val(0);
		}

		// if (flag && +agentNameType !== 448) $('#postPonyExpressDiv').css('display', 'none');
		$('.editAdditionalInfoBox')[+agentNameType === 448 ? 'removeClass' : 'addClass']('hide');//DHL编辑添加附加信息
	} else if(agentNameType == 256 || agentNameType == 419){
		// 中乌速递乌克兰专线
		expressAjax();
		$('#smtExpressDiv').css('display','none');
		$('#postPonyExpressDiv').css('display','none');
        $('#heLianExpressDiv').css('display', 'none');
		$('#zwsdWklExpressDiv').css('display', '');
		if (agentNameType != 419) {
            $(".kilimallGs").hide();
		}
	} else if(agentNameType == 353 || (agentNameType == 704 && apacPickUpType == 1) || (agentNameType == 3 && isBack == 1) || (codType == 1 && isBack == 1)) {
        // 合联物流
        $('#smtExpressDiv').css('display','none');
        $('#zwsdWklExpressDiv').css('display','none');
        $('#postPonyExpressDiv').css('display', 'none');
        $('#heLianExpressDiv').css('display', '');
    }else {
		// 隐藏速卖通物流承运商设置
		$('#smtExpressDiv').css('display','none');
		$('#postPonyExpressDiv').css('display', 'none');
		$('#zwsdWklExpressDiv').css('display', 'none');
        $('#heLianExpressDiv').css('display', 'none');
	}

	if (agentPackageCountType == 1) {
		$("[name='agentPackageCountDisplay']").css("display", "");
	} else {
		$("[name='agentPackageCountDisplay']").css("display", "none");
	}

	//判断选中的物流方是否
    if(updateShipInfoAuthSelectVal && updateShipInfoAuthSelectVal === updateShipInfoAuthSelect && behindTrackNumberType){
        $trackingNumber.addClass('hide');
        $reApplayTrackBtn.addClass('hide');
        $('#trackingNumberBox').removeClass('hide').css('display','');
    }else{
        $trackingNumber.removeClass('hide');
        $reApplayTrackBtn.removeClass('hide');
        $('#trackingNumberBox').addClass('hide');
	}
	if(val == 0){
		$("#trackingNumber").prop('disabled', false);
	}
};

/** 设置速卖通线上发货设置 **/
var setSmtOnline = function(){
	var $expressTd = $('#expressTd'),
		$expressTrackNum = $('#expressTrackNum'),
		$expressInput = $('#expressInput');

	$expressTd.find('.expressSpan').remove();
	$expressTrackNum.parent().find('.expressSpan').remove();

	var $updateShipInfoAuthSelect = $('#updateShipInfoAuthSelect option:selected'),
		apacPickUpType = $updateShipInfoAuthSelect.attr('apacPickUpType'),		// 揽收类型 0  上门揽收  1   快递运输到仓库    2  卖家自送到仓库
		providerType = $updateShipInfoAuthSelect.attr('providerType');			// 物流方式类型  1:中俄航空  2：4PX

	if((apacPickUpType == 0 || apacPickUpType == 2) && providerType != 1){
		$('#expressSelect, #expressSelect_chosen').css('display', 'none');
		$expressInput.parent().css('display', 'none');
		if(apacPickUpType == 0){ //上门揽收
			$expressTd.append("<span class='expressSpan'>上门揽收</span>");
		}else{					// 卖家自送到仓库
			$expressTd.append("<span class='expressSpan'>卖家自送到仓库</span>");
		}
		var trackNum = '无需填写';
		$expressTrackNum.css('display', 'none').after("<span class='expressSpan'>"+trackNum+"</span>");
	} else {
		expressAjax();
		var expressId = $('#expressId').val(),
			name = $('#expressNameHidden').val(),
			$expressSelect = $('#expressSelect');

		if(expressId == -1 && name !== '上门揽收' && name !== '卖家自送到仓库'){
			str = '<div class="form-group has-error has-feedback" style="margin:0;"><input type="text" value="" id="expressInput" placeholder="请输入" class="form-control" style="border-color:#ccc"/><span class="glyphicon glyphicon-remove form-control-feedback inputClose" style="right:0;color:#999;pointer-events:auto;"></span></div>';
			$expressTd.html(str);
			$expressInput.val(name);
			$expressSelect.html('');
		}else{
			$expressInput.remove();
			if($expressSelect.val() == undefined){
				$expressTd.append('<select class="form-control" id="expressSelect"><option value="0">请选择</option></select>');
				expressAjax();
			}
		}
		if($expressSelect.val() < 0){
			$expressSelect.val('0');
		}
		$expressSelect.chosen('destroy').chosen({
            search_contains: true//注册插件
        });
        $('#expressSelect_chosen').css('width','278px');

        $expressInput.parent().css('display', '');
		$expressTrackNum.val('').css('display', '');
	}

	var fCode = $.trim($('#detailPackageFcode').val()),
		orderState = $('#detailPackageState').val(),
		commitPlatform = $('#detailCommitplatformStatus').val(),
		$smtPackageExpressTr = $('#smtPackageExpressTr');

	if(fCode && (orderState === 'processed' || orderState === 'allocated_has' || orderState === 'allocated_out' ||
		(orderState === 'shipped' && commitPlatform !== 'fail'))){
		$smtPackageExpressTr.css('display', 'none');
		var expressName = $('#expressNameHidden').val(),
			expressNum = $('#expressNumberHidden').val();

		if(expressName === '上门揽收'){
			expressName = '上门揽收';
			expressNum  = '无需填写';
		}else if(expressName === '卖家自送到仓库'){
			expressName = '卖家自送到仓库';
			expressNum  = '无需填写';
		}
		var isBatteryStr = '否';
		if($('#isBatteryHidden').val() === '1'){
			isBatteryStr = '是';
		}
		var isLiquidStr = '否';
		if($('#isLiquidHidden').val() === '1'){
			isLiquidStr = '是';
		}
		var str = '<tr class="smtExpressName"><td style="width:120px;max-width:120px;">'+expressName+'</td><td style="width:120px;max-width:120px;">'+expressNum+'</td><td style="width:80px;max-width:80px;">'+isBatteryStr+'</td><td style="width:80px;max-width:80px;">'+isLiquidStr+'</td></tr>';
		$smtPackageExpressTr.parent().find(".smtExpressName").remove();
		$smtPackageExpressTr.after(str);

	} else {
		$smtPackageExpressTr.css('display', '');
	}
};

/** 验证是否数字 **/
var validateNum = function(val, id, errMsg){
	if(val == '' || val == null || val == undefined){
		$.fn.message({type:"error",msg:errMsg+"不能为空！"});
		$("#"+id).focus();
		return true;
	}
	var reg = /^\d+(\.\d{1,2})?$/;
	if(!reg.test(val)){
		$.fn.message({type:"error",msg:errMsg+"格式不对，请输入数字类型！"});
		$("#"+id).focus();
		return true;
	}
	var $updateShipInfoAuthSelect = $('#updateShipInfoAuthSelect'),
	    $updateShipInfoAuthSelectOpt = $updateShipInfoAuthSelect.find('option:selected'),
	    agentPackageCountType = $updateShipInfoAuthSelectOpt.attr('agentPackageCountType');
	if (agentPackageCountType == 1 && id == 'agentPackageCount' && (val <= 0 || val > 40)) {
		$.fn.message({type: "error", msg: "包裹数量不得小于等于0或者大于40"});
		$("#" + id).focus();
		return true;
	}
	return false;
};

/**  保存订单的物流方式  **/
var updateOrderProvider = function(packState){
	$('#isEditState').val('save');
	var $updateShipInfoAuthSelect = $('#updateShipInfoAuthSelect'),
        $updateShipInfoAuthSelectOpt = $updateShipInfoAuthSelect.find('option:selected'),
		agentType  = $updateShipInfoAuthSelectOpt.attr('agentype'),
		allotType  = $updateShipInfoAuthSelectOpt.attr('allotType'),
		agentNameType  = $updateShipInfoAuthSelectOpt.attr('agentNameType'),
		agentApAuthName = $updateShipInfoAuthSelectOpt.text(),		// 物流方式名称
		apAuthId = $updateShipInfoAuthSelect.val(),							// 物流方式ID
		packageId= $('#detailPackageId').val(),											// 包裹ID
		apacPickUpType = $updateShipInfoAuthSelectOpt.attr('apacPickUpType'),	// 揽收类型   0 上门揽收   1  快递运输到仓库   2  卖家自送到仓库
		providerType   = $updateShipInfoAuthSelectOpt.attr('providerType'),	// 物流方式类型  1:中俄航空  2：4PX
		showCodAmount = $updateShipInfoAuthSelectOpt.attr('isBack'),		// 出口易是否显示COD金额
		sizeType = $updateShipInfoAuthSelectOpt.attr('sizeType'),		// 出口易是否显示COD金额
		agentPackageCountType = $updateShipInfoAuthSelectOpt.attr('agentPackageCountType'),		// 包裹数量
		expressId = $('#expressSelect').val(),											// 国内快递ID
		expressName  = $('#expressSelect option:selected').text();						// 国内快递名称

	var goodVolume = $('#goodVolume').val() == undefined ? 0 : $('#goodVolume').val(); // 体积
	var goodPack = $('#goodPack').val() == undefined ? 0 : $('#goodPack').val(); // 是否带打包
	if(expressId == undefined && (apacPickUpType == 1 || providerType == 1)){
		expressName = $('#expressInput').val();
		expressId = -1;
	}
	var agentRadio = $("input[name='agentRadio']:checked").val();						// 获取单号方式
	if(agentRadio == 0){
		agentType = 0;
		allotType = 0;
		agentNameType  = 0;
		apacPickUpType = 0;
		providerType = 0;
		expressName  = '';
		agentApAuthName = $('#updateShipInfoAuthSelect1 option:selected').text();
		apAuthId = $('#updateShipInfoAuthSelect1').val();
	}
	var logisticFeeSpan = '';
	if(agentApAuthName.indexOf('[￥') !== -1){
		var arr = agentApAuthName.split('[￥');
		agentApAuthName = arr[0];
		logisticFeeSpan = arr[1].substring(0, arr[1].lastIndexOf(']'));
	}

	var trackingNumber = $('#trackingNumber').val(),									// 跟踪单号
        $expressTrackNum = $('#expressTrackNum'),
	    expressTrackNum = $.trim($expressTrackNum.val()),									// 快递单号
	    length = $('#postLength').val(),												// postPony相关开始
	    width = $('#postWidth').val(),
	    height = $('#postHeight').val(),
	    weight = $('#postWeight').val(),
	    lengthUnit = $('#lengthUnit').val(),
	    weightUnit = $('#weightUnit').val(),											// postPony相关结束
        codAmount = $('#heLianExpressCodAmount').val(),                               // 合联相关
     	fCode = $('#detailPackageFcode').val(),
		agentPackageCount = $("#agentPackageCount").val();

	if(+agentNameType === 22){
	    if(+apacPickUpType === 1 && expressTrackNum && expressTrackNum.toLowerCase() === 'none') {
			if(!$('.trackNumErrorMsg').length) {
				$updateShipInfoAuthSelect.addClass('border-red').closest('td').append('<div class="f-red trackNumErrorMsg">快递单号不能输入none</div>');
			}
            return;
        }
		// 速卖通线上发货
		if((apacPickUpType == 1 || providerType == 1) && expressId == 0 && expressName === '请选择' && expressTrackNum){
			$.fn.message({type:"error", msg:"请选择国内快递!"});
			return;
		}
		if(expressTrackNum && !expressName && (apacPickUpType == 1 || providerType == 1)){
			$.fn.message({type:"error", msg:"请输入国内快递!"});
			return;
		}
		//先不验证必填了，可在分拨组包时填写
		// if((apacPickUpType == 1 || providerType == 1) &&(!expressTrackNum)){
		// 	$.fn.message({type:"error", msg:"请输入快递单号！"});
		// 	return;
		// }
		if((apacPickUpType == 0 || apacPickUpType == 2) && providerType != 1){
			if(apacPickUpType == 0){
				expressName = '上门揽收';
			}else{
				expressName = '卖家自送到仓库';
			}
			expressId = -1;
			expressTrackNum = '无需填写';
		}
		if((apacPickUpType == 0 || apacPickUpType == 2)  && providerType == 2){
			expressTrackNum = '无需填写';
		}
	} else if(agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1){
		// postPony物流
		var a = validateNum(length,'postLength','长度');
		if(a){
			return;
		}
		var b = validateNum(width,'postWidth','宽度');
		if(b){
			return;
		}
		var c = validateNum(height,'postHeight','高度');
		if(c){
			return;
		}
		if(agentNameType != 655 && agentNameType != 448 && agentNameType != 734 && sizeType != 1){
			var d = validateNum(weight,'postWeight','重量');
			if(d){
				return;
			}
		} else if (agentPackageCountType == 1) {
			var c = validateNum(agentPackageCount, 'agentPackageCount', '包裹数量');
			if (c) {
				return;
			}
		}
		if(agentNameType == 655){
			expressId = $('#inlandExpressCode').val();
			expressName = $('#inlandExpressCode option:selected').text();
			expressTrackNum = $('#inlandExpressNumber').val();
		}
	} else if(agentNameType == 256 || agentNameType == 419){
		// 中乌速递乌克兰专线
		expressId = $('#zwsdExpressSelected').val();
		expressName = $('#zwsdExpressSelected option:selected').text();
		expressTrackNum = $('#zwsdExpressTrackNumber').val();
		if(expressId == 0 && (expressName === '请选择' || expressName === '')){
			$.fn.message({type:"error", msg:"请选择国内快递!"});
			return;
		}
		if(!expressTrackNum){
			$.fn.message({type:"error", msg:"请输入快递单号！"});
			return;
		}
        var reg = /^[0-9]*[1-9][0-9]*$/;
		if (agentNameType == 419 && !reg.test(goodVolume)) {
            $.fn.message({type:"error", msg:"请输入大于0的整数体积！"});
            return;
		}
	}
	var isChecked = $('#isBattery').is(':checked'),										// 是否含电
	    isBattery = 0,
	    isBatteryHtml = '--';
	if(isChecked){
		isBattery = 1;
		isBatteryHtml = '是';
	}
	var isLiquidChecked = $('#isLiquid').is(':checked'),								// 是否液体
	    isLiquid = 0,
	    isLiquidHtml = '--';
	if(isLiquidChecked){
		isLiquid = 1;
		isLiquidHtml = '是';
	}
	var isHomeCheck = $('#isHomeAddr').is(':checked'),									// 是否家庭地址
        isHomeAddrHtml = '否',
	    isHomeAddr = 0;
	if(isHomeCheck){
		isHomeAddr = 1;
		isHomeAddrHtml = '是';
	}
	if(apAuthId == '' || apAuthId == 0){
		$.fn.message({type:"error", msg:"请选择物流方式!"});
		return;
	}
	if(packState === 'processed' || packState === 'allocated_has' || packState === 'allocated_out' || packState === 'allocated_exception' || packState === 'shipped'){
		if(!($updateShipInfoAuthSelect.val() === updateShipInfoAuthSelectVal && behindTrackNumberType) && !trackingNumber){
			$.fn.message({type:"error", msg:"请输入跟踪单号！"});
			$('#trackingNumber').focus(); //使跟踪单号获取焦点
			return;
		}
	}
	var oldAgentNameType = $('#agentNameType').val(),	// 原物流方式
	    wishCountry = $('#wishCountry').val(),		// wish发货国家
		$walmartCountryCode = $('#walmartCountryCode'),
		walmartCountry = $walmartCountryCode.val() || '';			// walmart发货国家

	if(!wishCountry){
		wishCountry = '';
	}
	var wishCountryCh = $('#wishCountry option:selected').attr('data-ch');			// wish发货国家
	if(!wishCountryCh){
		wishCountryCh = '';
	}

	//如果是Walmart的订单物流设置保存，且发货地没有选择，报错提示
	if ($('[name="agentRadio"]:checked').val() === '0' && $walmartCountryCode.length && !walmartCountry) {
		$.fn.message({type: 'error', msg: '请选择Walmart发货地！'});
		$walmartCountryCode.next('.chosen-container').find('input:text').focus();
		return;
	}

	$('#loading').modal('show');
	$.ajax({
		type: 'POST',
		url: 'package/uploadTrackNum.json',
		data: {
            authId:apAuthId,
            packageId:packageId,
            expressId:expressId,
            expressName:expressName,
            trackNum:trackingNumber,
            expressTrack:expressTrackNum,
            isBattery:isBattery,
            isLiquid:isLiquid,
            length:length,
            width:width,
            height:height,
            lengthUnit:lengthUnit,
            weight:weight,
            weightUnit:weightUnit,
            isHomeAddr:isHomeAddr,
            agentNameType:agentNameType,
            wishCountry : wishCountry || walmartCountry,
            codAmount : codAmount,
            fCode : fCode,
            goodVolume : goodVolume,
            pack : goodPack,
			agentPackageCount: agentPackageCount
		},
		dataType: 'json',
		success: function(data){
			$('#loading').modal('hide');
			var code = data.code;
			if(!+code){
				var $trackNumberDiv = $('#trackNumberDiv');
				var codType = $updateShipInfoAuthSelectOpt.attr('codType');

                if(!($updateShipInfoAuthSelect.val() === updateShipInfoAuthSelectVal && behindTrackNumberType)){
                    behindTrackNumberType = false;
                    $trackNumberDiv.closest('div.form-group').find('label').empty().html('跟踪单号：');
				}else{
                    trackingNumber = fCode;
                    $trackNumberDiv.closest('div.form-group').find('label').empty().html('物流商单号：');
                }

				$.fn.message({type:"success", msg:"保存物流信息成功!"});
				$('#shippingProviderSpan').removeClass('glyphicon-remove fRed').addClass('glyphicon-ok fGreen');
				$('#shippingProviderTr').html(strEscapeCharacter(agentApAuthName));
                if(apAuthId && apAuthId >0){
                    $('#agentProviderDiv').html('<a href="providerAuth/editSetIndex.htm?apAuthId='+apAuthId+'&fromOrder=1" target="_blank">'+ strEscapeCharacter(agentApAuthName) +'</a>');
				}else{
					if(wishCountryCh){
						wishCountryCh = '（' + wishCountryCh + '）';
					}
                    $('#agentProviderDiv').html(strEscapeCharacter(agentApAuthName) + wishCountryCh);
				}
				$('#detailPackageAuthId').val(apAuthId);
				$('#expressId').val(expressId);
				if(agentNameType == 655) {
					$('#alibabaExpress').text(expressName);
					$('#alibabaExpressNumber').text(expressTrackNum);
				}
				$('#expressNameHidden').val(expressName);
				$('#detailPackageTrackNum').val(trackingNumber);
                $trackNumberDiv.html(trackingNumber).addClass('col-sm-3 pTop6');
				$('#expressNumberHidden').val(expressTrackNum);
				$('#isBatteryHidden').val(isBattery);
				$('#isLiquidHidden').val(isLiquid);
				$('#agentType').val(agentType);
				$('#agentNameType').val(agentNameType);
				$('#allotType').val(allotType);
				$('#expressNameHtml').html(expressName);
				$('#expressNumberHtml').html(expressTrackNum);
				$('#isBatteryHtml').html(isBatteryHtml);
				$('#isLiquidHtml').html(isLiquidHtml);

				var weightUnitHtml = '盎司';
				if(weightUnit === 'g'){
					weightUnitHtml = '克';
				}
				$('#lengthHtml').html(length);												// postPony相关开始
				$('#widthHtml').html(width);
				$('#heightHtml').html(height);
				$('#lengthUnitHtml').html(lengthUnit);
				$('#weightHtml').html(weight);
				$('#weightUnitHtml').html(weightUnitHtml);
				$('#isAddrHomeHtml').html(isHomeAddrHtml);									// postPony相关结束
				$('#agentPackageCountHtml').html(agentPackageCount);									// postPony相关结束
				if (agentNameType == 419) {
                    // kilimall选择物流方式
                    $('#expressVolumeHidden').val(goodVolume);
                    $('#expressPackHidden').val(goodPack);
                    $("#goodVolumeContent").html(goodVolume);
                    var goodPackContent = goodPack == 1 ? '需要' : '不需要';
                    $("#packIsNeed").html(goodPackContent);
				}

                $('#heLianCodAmountHtml').html(codAmount);									// 合联相关开始
                $('#heLianCodAmountHidden').val(codAmount);									// 合联相关结束

				$('#zwsdExpressNameHtml').html(expressName);
				$('#zwsdExpressNumberHtml').html(expressTrackNum);
                $('#inlandExpressNumberHidden').val(expressTrackNum);

				if(agentNameType == 22){
					// 显示速卖通物流承运商设置
					$('#smtAgentDiv').css('display','');
					$('#postPonyDiv').css('display','none');
					$('#zwsdAgentDiv').css('display','none');
                    $('#heLianDiv').css('display','none');

					// 速卖通线上发货保存成功后将对应物流方式的快递保存
					// 当前选中的物流方式值  expressId揽收方式
					smtOrderDetailSaveExpress($('#updateShipInfoAuthSelect').val(), expressId);
				} else if(agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1){
					// postPony
					$('#smtAgentDiv').css('display','none');
					$('#zwsdAgentDiv').css('display','none');
					if (codType == 1) {
						$('#heLianDiv').css('display','');
					} else {
						$('#heLianDiv').css('display','none');
					}
					$('#postPonyDiv').css('display','');
				} else if(agentNameType == 256 || agentNameType == 419){
					// 中乌速递乌克兰专线
					$('#smtAgentDiv').css('display','none');
					$('#postPonyDiv').css('display','none');
                    $('#heLianDiv').css('display','none');
					$('#zwsdAgentDiv').css('display','');
					if (agentNameType != 419){
                        $('.kilimallContent').css('display', 'none');
					}
				} else if(agentNameType == 353 || (agentNameType == 704 && apacPickUpType == 1) || (agentNameType == 3 && showCodAmount == 1) || (codType == 1 && showCodAmount == 1)) {
                    // 合联专线
                    $('#smtAgentDiv').css('display','none');
                    $('#postPonyDiv').css('display','none');
                    $('#zwsdAgentDiv').css('display','none');
                    $('#heLianDiv').css('display','');
                }else {
					// 隐藏速卖通物流承运商设置
					$('#smtAgentDiv').css('display','none');
					$('#postPonyDiv').css('display','none');
					$('#zwsdAgentDiv').css('display','none');
                    $('#heLianDiv').css('display','none');
				}

				if (agentPackageCountType == 1) {
					$("[name='agentPackageCountDisplay']").css("display", "");
				} else {
					$("[name='agentPackageCountDisplay']").css("display", "none");
				}

				// 海外仓
				if(agentNameType >= 10000){
					$('#orderPackageStockSpan').html(data.overseaWarehoseName).css('display','');
					$('#platform').val(data.platform);
					$('#orderPackageStockSelectId').css('display','none');
				} else {
					$('#orderPackageStockSpan').text('').css('display','none');

					if(oldAgentNameType >= 10000){
						$('#orderPackageStockSelectId').val(data.storageId);
					}
					$('#orderPackageStockSelectId').css('display','');
				}
				// 在未编辑页面申请单号按钮和上传按钮隐藏
				$('#uploadTrackNumBtn').closest('div').addClass('myj-hide');
				/*$("#uploadTrackNumInput").hide();*/

				// 打印面单按钮
				$('#detailPrintMbBtn').attr('onclick','printMb("' + packageId+'","'+apAuthId+'");');
				cancelShipInfo();
				$('#logisticFeeSpan').html('￥' + logisticFeeSpan);
			} else {
				$.fn.message({type:"error", msg:data.msg});
			}
			$('#packageDetailModal').modal('hide').modal('show');
			if (packState === 'paid' || packState === 'approved') {
				dxmPackageDetail(packageId);
			}
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};
/************************** 订单列表end **************************/

/** 包裹详情 **/
var dxmPackageDetail = function (packageId, callback, isAddrException, isAdd, obj) {
    var history = $("#keepState").data("history"),
        num = $('#contentTabNum').val(),
		$proQuoteType = $('#wareHoseProductsQuoteModal').find('.proQuoteType');

    if (obj) {
		packageId = $(obj).closest('tr').attr('data-orderid');
	}

	if ($proQuoteType.length) $proQuoteType.val('');//点击订单详情的时候，先清一下这个历史数据
	if(!history){
		history = "";
	}
	var url = 'package/detail.htm';
	if(+isAdd === 1){
		url = 'package/addProductDetail.htm';
	}
	$('#dxmPackageDetailDiv').empty();
	$('#loading').modal('show');
	
	//测试数据
	var data = packageDetailData();
	$('#loading').modal('hide');
	$('#dxmPackageDetailDiv').html(data);
	$('#packageDetailModal').modal('hide').modal('show');
	var $keepState = $('#keepState'),
		orderIds = $keepState.data('orderIds'),//订单id数组
		currOrderNum= $keepState.data('currOrderNum'),//当前订单的id在数组中的位置
		$dailySaleSetD = $('#dailySaleSetID'),
		$originSaleSetBtnID = $('#originSaleSetBtnID'), //还原按钮
		dailySale = $dailySaleSetD.attr('data-sale'),
		dailySet = $dailySaleSetD.attr('data-set');
	//显示或隐藏还原按钮
	$originSaleSetBtnID[+dailySale === 1 && +dailySet === 1 ? 'addClass': 'removeClass']('myj-hide');
	currOrderNum=parseInt(currOrderNum);
	var currPage= $('#pageNo').val() || 1,//当前页
		totalPage= $('#totalPage').val() || 30;//总页数
	currPage = parseInt(currPage);
	totalPage = parseInt(totalPage);
	if(orderIds!=null) {
		if(orderIds.length === 1){//当前页只有一条
			$('#upbtnForOrder').attr('onclick','');
			$('#downbtnForOrder').attr('onclick','');
			$('#upOrDownDiv').css('display','none');
		}else if (+currOrderNum === -1) {
			for (i = 0; i < orderIds.length; i++) {
				if (packageId == orderIds[i]) {
					currOrderNum = i;
					break;
				}
			}
	        $keepState.data('currOrderNum',currOrderNum);
		}
		if(+currPage === 1 && +currOrderNum === 0){//第一页第一条
			$('#upbtnForOrder').attr('onclick','').addClass('btn-disabled');
			$('#upShow').attr('data-original-title','已经是第一个了');
		}else if(+currPage === +totalPage && +currOrderNum === (orderIds.length-1)){//最后一页最后一条
			$('#downbtnForOrder').attr('onclick','').addClass('btn-disabled');
			$('#downShow').attr('data-original-title','已经是最后一个了');
		}
	}
	$('[data-toggle="popover"]').popover({
		trigger: 'hover'
	});
	// 回调
	if (callback) {
		callback();
	}
	// 设置报关总额
	allCustomsForm();
	refreshOrderProfit(1,packageId.toString());
	
	$('#contentTab li[data-value="'+num+'"]').find('a').click();//找到上一次点击的tab位置，然后模拟点击切换到上次点击的tab位置
	$('div.listImgIn').picZoom({
		imgWidth:'296',
		imgHeight:'296',
		divWidth:'300',
		divHeight:'300',
		type: 'order'
	})
	return ;
	$.ajax({
		type: "POST",
		url: url,
		data: {"packageId": packageId, "isAddrException": isAddrException, "history":history},
		dataType: "html",
		success: function (data) {
			$('#loading').modal('hide');
			$('#dxmPackageDetailDiv').html(data);
			$('#packageDetailModal').modal('hide').modal('show');
			var $keepState = $('#keepState'),
				orderIds = $keepState.data('orderIds'),//订单id数组
				currOrderNum= $keepState.data('currOrderNum'),//当前订单的id在数组中的位置
				$dailySaleSetD = $('#dailySaleSetID'),
				$originSaleSetBtnID = $('#originSaleSetBtnID'), //还原按钮
				dailySale = $dailySaleSetD.attr('data-sale'),
				dailySet = $dailySaleSetD.attr('data-set');
            //显示或隐藏还原按钮
			$originSaleSetBtnID[+dailySale === 1 && +dailySet === 1 ? 'addClass': 'removeClass']('myj-hide');
			currOrderNum=parseInt(currOrderNum);
			var currPage= $('#pageNo').val() || 1,//当前页
				totalPage= $('#totalPage').val() || 30;//总页数
			currPage = parseInt(currPage);
			totalPage = parseInt(totalPage);
			if(orderIds!=null) {
				if(orderIds.length === 1){//当前页只有一条
					$('#upbtnForOrder').attr('onclick','');
					$('#downbtnForOrder').attr('onclick','');
					$('#upOrDownDiv').css('display','none');
				}else if (+currOrderNum === -1) {
					for (i = 0; i < orderIds.length; i++) {
						if (packageId == orderIds[i]) {
							currOrderNum = i;
							break;
						}
					}
                    $keepState.data('currOrderNum',currOrderNum);
				}
				if(+currPage === 1 && +currOrderNum === 0){//第一页第一条
					$('#upbtnForOrder').attr('onclick','').addClass('btn-disabled');
					$('#upShow').attr('data-original-title','已经是第一个了');
				}else if(+currPage === +totalPage && +currOrderNum === (orderIds.length-1)){//最后一页最后一条
					$('#downbtnForOrder').attr('onclick','').addClass('btn-disabled');
					$('#downShow').attr('data-original-title','已经是最后一个了');
				}
			}
			$('[data-toggle="popover"]').popover({
				trigger: 'hover'
			});
			// 回调
			if (callback) {
				callback();
			}
			// 设置报关总额
			allCustomsForm();
            refreshOrderProfit(1,packageId.toString());

            $('#contentTab li[data-value="'+num+'"]').find('a').click();//找到上一次点击的tab位置，然后模拟点击切换到上次点击的tab位置
			$('div.listImgIn').picZoom({
				imgWidth:'296',
				imgHeight:'296',
				divWidth:'300',
				divHeight:'300',
				type: 'order'
			})
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	$('#executeChangePackageNumModel').empty();
};

/** 设置报关总额 **/
var allCustomsForm = function(){
	var allDev = 0;
	var allWeight = 0;
	$("#customsInformation").find(".tdCfCustom").each(function(){
		var dev = parseFloat($(this).find(".deValSpan").text());
		if(isNaN(dev)){
			dev = 0;
		}
		var weight = parseInt($(this).find(".weightSpan").text());
		if(isNaN(weight)){
			weight = 0;
		}
		var count  = parseInt($(this).find(".cfProductCount").text());
		allDev += dev * count;
		allWeight += weight * count;
	});
	$("#allCustomsFormSpan").html("（总价："+ allDev.toFixed(2) + " USD 总重量："+ allWeight +" g）");
};

/** 显示包裹报关信息 **/
var showPackCustomsForm = function(){
	confirmUpdateCfOrAddr();
	var orderId = $("#detailPackageId").val();
	var platform = $('#detailPlatform').val();
	$.ajax({
		type: "POST",
		url: 'customsForm/getById.json',
		data: {"orderId":orderId},
		dataType: "json",
		success: function(data){
			var customsForm = data.customsForm;
			if(customsForm == null){
				customsForm = "";
			}
			$("#packNameCh").val(customsForm.nameCh);
			$("#packNameEn").val(customsForm.nameEn);
			$("#packDetailHsCode").val(customsForm.hsCode);
			$("#packMaterial").val(customsForm.material);
			$("#packPurpose").val(customsForm.purpose);
			$("#packWeight").val(customsForm.weight);
			$("#packDeclaredValue").val(customsForm.declaredValue);
			$("#packDeclaredCurrency").val(customsForm.declaredCurrency);
            if (customsForm == "" || customsForm.isBattery == 0) {
                $('#packDetailIsBattery').prop("checked", false);
                $('#batteryLevel').addClass('hide');
            } else {
                $('#packDetailIsBattery').prop('checked', true);
                $("#batteryLevel option[value='" + customsForm.isBattery + "']").prop('selected', true);
                $('#batteryLevel').removeClass('hide');
            }
            $('#packDetailIsAneroidMarkup').prop('checked', customsForm && +customsForm.isAneroidMarkup === 1);
            $('#packDetailIsSpecialGoods').prop('checked', customsForm && +customsForm.isSpecialGoods === 1);
			if(customsForm == ""){
				$("#handCfTotalPrice").text("0");
				$("#handCfTotalWeight").text("0");
			} else {
				$("#handCfTotalPrice").text(customsForm.declaredValue*customsForm.declaredCurrency);
				$("#handCfTotalWeight").text(customsForm.weight*customsForm.declaredCurrency);
			}
			$('#customsDeclaration').val('');
			$('.div-dxmSelectionSort').find('#orderCustomsDeclaration span[data-names="nodeName"]').text('---可选择引用报关模板---');
			$('#customsDeclaration').closest('#messageTemplateSelect').find('div.templateMsg').removeClass('myj-hide');
			$("#packageCustomsFormModal").modal("show");
		},
		error:function(){
			$('#loading').modal('hide');
		}
	});
};

/** 更新包裹报关信息状态 **/
var updatePackCfUsed = function () {
	var orderId = $("#detailPackageId").val();
	$.ajax({
		type: "POST",
		url: 'customsForm/updatePackCfUsed.json',
		data: {"orderId": orderId},
		dataType: "json",
		success: function (data) {
			$("#packCustomsFormTable").css("display", "none");
			$("#customsFormTable").css("display", "");
			$("#packCfUsed").val(false);
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/*** 执行修改包裹报关信息 ***/
var updatePackCustomsForm = function () {
	var orderId = $('#detailPackageId').val();
	var nameCh = $.trim($('#packNameCh').val());
	var nameEn = $.trim($('#packNameEn').val());
	var hsCode = $.trim($('#packDetailHsCode').val());
	var material = $.trim($('#packMaterial').val());
	var purpose = $.trim($('#packPurpose').val());
	var weight = $('#packWeight').val();
	var declaredValue = $('#packDeclaredValue').val();
	var declaredCurr = $('#packDeclaredCurrency').val();
	var isBattery = 0,
		isAneroidMarkup = $('#packDetailIsAneroidMarkup').is(':checked') ? 1 : 0, //是否含非液体化妆品
		isSpecialGoods = $('#packDetailIsSpecialGoods').is(':checked') ? 1 : 0;   //是否包含特货 (敏感货)

	if ($('#packDetailIsBattery').is(':checked')) {
		isBattery = $('#batteryLevel').val();
	}

	var reg = /^[0-9]*$/;
	var regVal = /^\d+(\.\d{1,2})?$/;
	// 验证为空
	if (nameCh == null || nameCh.length == 0) {
		$.fn.message({type: 'error', msg: '报关信息中文名称不能为空!'});
		return;
	}
	if (nameEn == null || nameEn.length == 0) {
		$.fn.message({type: 'error', msg: '报关信息英文名称不能为空!'});
		return;
	}
	if (/[\u4E00-\u9FA5]/g.test(nameEn)) {
		$.fn.message({type: 'error', msg: '英文名称不能含有汉字！'});
		return;
	}
	if (!declaredValue.match(regVal) || declaredValue <= 0) {
		$.fn.message({type: 'error', msg: '申报金额请输入大于0的数字,小数点保留1-2位'});
		return;
	}
	if (!reg.test(weight)) {
		$.fn.message({type: 'error', msg: '申报重量单位为（g）请输入大于等于0的整数'});
		return;
	}
	if (!reg.test(declaredCurr) || !+declaredCurr) {
		$.fn.message({type: 'error', msg: '申报数量请输入大于0的整数'});
		return;
	}
	$.ajax({
		type: 'POST',
		url: 'customsForm/updatePackCustomForm.json',
		data: {
			orderId: orderId,
			nameCh: nameCh,
			nameEn: nameEn,
			weight: weight,
			declaredValue: declaredValue,
			declaredCurr: declaredCurr,
			material: material,
			purpose: purpose,
			hsCode: hsCode,
			isBattery: isBattery,
			isAneroidMarkup: isAneroidMarkup,
			isSpecialGoods: isSpecialGoods
		},
		dataType: 'json',
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: 'success', msg: '保存报关信息成功!'});
				var packCustomContent = nameCh + (nameEn === '' ? '' : '&nbsp;/&nbsp;') + nameEn + (declaredValue === '' ? '' : '&nbsp;/&nbsp;$') + declaredValue + (weight === '' ? '' : '&nbsp;/&nbsp;') + weight + (weight === '' ? '' : '（g）') + (hsCode === '' ? '' : '&nbsp;/&nbsp;') + hsCode + (declaredCurr === '' ? '' : '&nbsp;/&nbsp;') + declaredCurr;
				if (+isBattery === 1) {
					packCustomContent += '&nbsp;/&nbsp;含电（内电)';
				} else if (+isBattery === 2) {
					packCustomContent += '&nbsp;/&nbsp;含电（纯电)';
				}
				if (+isAneroidMarkup) packCustomContent += '&nbsp;/&nbsp;含非液体化妆品';
				if (+isSpecialGoods) packCustomContent += '&nbsp;/&nbsp;特货 (敏感货)';
				$('#tdPackCustomsForm').html(packCustomContent);
				$('#customsInformationSpan').removeClass('glyphicon-remove fRed').addClass('glyphicon-ok fGreen');
				$('#packCustomsFormTable').css('display', '');
				$('#customsFormTable').css('display', 'none');
				$('#packCfUsed').val(true);
				$('.customsInfo .customsAmount').text($('#handCfTotalPrice').text());
				$('.customsInfo .customsWeight').text($('#handCfTotalWeight').text());
				closeDiv('packageCustomsFormModal');
				cancelCustomsForm();
			} else {
				$.fn.message({type: 'error', msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 修改地址和报关信息提示框 **/
var confirmUpdateCfOrAddr = function(){
	var tarckNum = $("#detailPackageTrackNum").val();
	var fCode = $("#detailPackageFcode").val();
	var $detailCountry = $('#detailCountry');
	if((tarckNum !== '' && tarckNum != null) || (fCode !== '' && fCode != null)){
		var tipContent = $('#orderStatus').val() === 'processed' ? '编辑内容后，必须将订单打回待处理并重新「申请运单号」后才能生效！直接在该页面「获取跟踪号」不会生效' : '编辑内容后，必须「更换运单号」才能生效！';
		myjAlert.alert({
			'close' : '<span></span>',
			'width' : 450,
			'content':'<span style="font-size:14px;color:red"><span style="font-weight: 600">重要提示：</span>' + tipContent + '</span>',
			'enter' :'我知道了'
		});
	}
	if(+$detailCountry.data('type')){
		$detailCountry.chosen();
		$detailCountry.data('type',0);
        $('#detailCountry_chosen').css('width', '170px');
	}
};

/** 关闭包裹详情 **/
var closePackCf = function () {
	closeDiv('packageCustomsFormModal');
	var packCfUsed = $("#packCfUsed").val();
	if (packCfUsed == 'true') {
		$("#pcfCheckBox").prop("checked", true);
	} else {
		$("#pcfCheckBox").prop("checked", false);
	}
};

/** 删除备注 **/
var deletePackageComment = function (id, obj) {
	var history = $("#keepState").data("history");
	if(!history) {
		history = "";
	}
	myjAlert.confirm({
		'content': '确定要删除该备注？',
		'callback': function (v) {
			if (v) {
				$.ajax({
					type: "POST",
					url: 'dxmPackageComment/delete.json',
					data: {"id": id,"history":history},
					dataType: "json",
					success: function (data) {
						if (data.code == -1) {
							$.fn.message({type: "error", msg: data.msg});
						} else {
							$.fn.message({type: "success", msg: "删除备注成功！"});
							$(obj).parent().parent().remove();
						}
					}
				});
			}
		}
	})
};

/** 包裹详情页显示订单详情 **/
var packageOrderDetail = function (orderId, val) {
	// 把原来的onclick事件替换
	if (val == 1) {
		// 扫描弹出订单详情
		dxmOrderDetail(orderId, scanOrderDetaiAfter);

	} else if (val == 2) {
		// 分拣包裹
		dxmOrderDetail(orderId);
	} else {
		// 包裹弹出订单详情
		dxmOrderDetail(orderId, packageOrderDetaiAfter);
	}
};

/** 提交至平台 **/
var isCommitPlatform = false;
var commitPlatform = function (packageId) {
	if (isCommitPlatform) {
		return;
	}
	isCommitPlatform = true;

	var state = $("#keepState").data("state");
	var successMsg = "虚拟发货成功！物流跟踪号已提交到平台！";
	if (state == 'shipped') {
		successMsg = "提交平台成功！";
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/commitPlatform.json',
		data: {
			"packageId": packageId
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: successMsg});
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();
			} else {
				/*2017.5.17 byzym 添加URL包裹*/
				var msg = strFilterUrl(data.msg);
				$.fn.message({type: "error", msg: msg});
			}
			isCommitPlatform = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isCommitPlatform = false;
		}
	});
};

/** 批量提交至平台  **/
var isBatchCommitPlatform = false;
var batchCommitPlatform = function (free) {
	if(isBatchCommitPlatform){
		return;
	}
	isBatchCommitPlatform = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if(packageIds == ""){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		isBatchCommitPlatform = false;
		return;
	}
	myjAlert.confirm({
		'content':'确定要虚拟发货（提交至平台）？<br> <span class="gray-c lh24">注意:禁止类型为收货地址变更的订单,无法虚拟发货</span>',
		'callback':function(v){
			if(v){
				if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
				$('#loading').modal('show');
				$.ajax({
					type: "POST",
					url: 'package/batchCommitPlatform.json',
					data: ajaxData,
					dataType: "json",
					success: function(data){
						if(data.code == 0){
							var successList = data.bor.successList;
							var failList 	= data.bor.failList;
							batchReturnProcess(successList, failList, "物流跟踪号已提交到平台！");
							if(free == 'free'){
								refreshFreeAjax();
							} else {
								refreshAjaxPage();
							}
						}else{
							/*2017.5.17 byzym 添加URL包裹*/
							var msg = strFilterUrl(data.msg);
							$.fn.message({type: "error", msg: msg});
						}
						isBatchCommitPlatform = false;
					},
					error:function(){
						$('#loading').modal('hide');
						isBatchCommitPlatform = false;
					}
				});
			} else {
				isBatchCommitPlatform = false;
			}
		}
	});
};

/** 批量提交至平台(忽略错误) **/
var isIngoreErrCommitPlatform = false;
var batchIngoreErrCommitPlatform = function () {

	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if(packageIds == ""){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		return;
	}
	if(isIngoreErrCommitPlatform){
		return;
	}
	isIngoreErrCommitPlatform = true;
	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchCommitPlatform.json',
		data: ajaxData,
		dataType: "json",
		success: function(data){
			if(data.code == 0){
				var successList = data.bor.successList;
				var failList 	= data.bor.failList;
				batchReturnProcess(successList, failList, "物流跟踪号已提交到平台！");
				refreshAjaxPage();
			}else{
				$.fn.message({type:"error", msg:data.msg});
			}
			isIngoreErrCommitPlatform = false;
		},
		error:function(){
			$('#loading').modal('hide');
			isIngoreErrCommitPlatform = false;
		}
	});
};

/** 批量发货  **/
var isBatchShip = false;
var batchShipGoods = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if(packageIds == ""){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		return;
	}
    var packageArr = packageIds.split(","),
		notPrintMdNum = 0,
		isPrintpackage,
		authId;
    for(var i=0;i<packageArr.length;i++){
        isPrintpackage = $('#printMd'+packageArr[i]);
		authId = $('#dxmAuthId'+packageArr[i]).val();
        if(isPrintpackage.length == 1 || authId == 0){
            continue;
        }
        notPrintMdNum += 1;
    }
    var contentTip = '确定要发货？',
		isoversea = $('#keepState').data('isoversea'); // -1: 非运单号申请 0：自营仓库 1：海外仓 2：小秘云仓
	if (notPrintMdNum > 0) {
		if (+isoversea === 1) { // 海外仓无需提示未打印面单
			contentTip = '当前选中' + packageArr.length + '条数据，确定要发货？';
		} else {
			contentTip = '<span style="line-height: 22px"><span class="fW600">当前选中' + (packageArr.length) + '条数据，</span><span class="fW600 fRed">有' + notPrintMdNum + '条数据未打印面单！</span></br>确定要发货？</span>';
		}
	}
	myjAlert.confirm({
		'content': contentTip,
		'callback':function(v){
			if(v){
                if(isBatchShip){
                    return;
                }
                isBatchShip = true;
                if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
				$('#loading').modal('show');
				$.ajax({
					type: "POST",
					url: 'package/batchShipGoods.json',
					data: ajaxData,
					dataType: "json",
					success: function(data){
						if(data.code == 0){
							var successList = data.bor.successList;
							var failList 	= data.bor.failList;
							batchReturnProcess(successList, failList, "订单已移入到「已交运」页！");
							refreshAjaxPage();
						}else{
							/*2017.5.17 byzym 添加URL包裹*/
							var msg = strFilterUrl(data.msg);
							$.fn.message({type: "error", msg: msg});
						}
						isBatchShip = false;
					},
					error:function(){
						$('#loading').modal('hide');
						isBatchShip = false;
					}
				});
			}
		}
	});
};

var showCancelCheckModal = function(commitStatus){
	if(commitStatus == 'success'){
		$('#cancelActionType3').prop("checked", true);
		$('#cancelActionType1').parent().css('display', 'none');
		$('#cancelActionType3').parent().css('display', '');
	} else {
		$('#cancelActionType1').prop("checked", true);
		$('#cancelActionType1').parent().css('display', '');
		$('#cancelActionType3').parent().css('display', 'none');
	}
};

/** 弹出取消框 **/
var showCancelModal = function(packageId, commitStatus){
	if(packageId > 0){
		showCancelCheckModal(commitStatus);
		$('#batchCancelPackageBtn').attr("onClick", "cancelShipGoods('"+ packageId +"');");
	} else {
		// 如果没有选中所有页，要判断用户是否已选择订单
		var s = '';
		var commit = '';
		var flag = false;
		$("input[name='packageId']:checked").each(function(){
			var v = $(this).val();
			if(s!=''){
				s = s + ",";
			}
			s = s + v;
			var c = $(this).attr("data-commit");
			if(commit == ''){
				commit = c;
			} else {
				if(commit != c){
					flag = true;
				}
			}
		});
		if(s == ''){
			$.fn.message({type:"error",msg:"请至少选择一个订单"});
			return;
		}
		if(flag){
			$.fn.message({type:"error",msg:"已虚拟发货和未虚拟发货的订单不支持一起批量取消发货，不能混合操作，请选择一个再【批量取消发货】"});
			return;
		}
		showCancelCheckModal(commit);
		$('#batchCancelPackageBtn').attr("onClick", "batchCancelShipGoods();");
	}
	$('#cancelConfirmModal').modal('show');
};

/** 批量取消发货  **/
var isBatchCancel = false;
var batchCancelShipGoods = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if(packageIds == ""){
		$.fn.message({type:"error",msg:"请至少选择一个订单"});
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		url: 'package/checkIsWaving.json',
		type: 'get',
		data: {packageIds: packageIds},
		dataType: 'json',
		success: function(data) {
			$('#loading').modal('hide');
			if (data.code) {
				myjAlert.confirm({
					content: data.msg + "确认取消吗？",
					callback: function(v){
						if(v){
							var exceptionAction = $("input[name='cancelActionType']:checked").val();
							if(exceptionAction != 1 && exceptionAction != 2 && exceptionAction != 3){
								$.fn.message({type: "error", msg: "请选择取消原因！"});
								return;
							}
							packageIds = getCheckBoxValByName("packageId");
							if(packageIds == ""){
								$.fn.message({type:"error",msg:"请至少选择一个订单"});
								return;
							}
							var packageArr = packageIds.split(",");
							var notPrintMdNum = 0;
							var isPrintpackage;
							var authId;
							for(var i=0;i<packageArr.length;i++){
								isPrintpackage = $('#printMd'+packageArr[i]);
								authId = $('#dxmAuthId'+packageArr[i]).val();
								if(isPrintpackage.length == 1 || authId == 0){
									continue;
								}
								notPrintMdNum += 1;
							}
							var contentTip = '确定要取消？';
							if(notPrintMdNum>0){
								contentTip = '<span style="line-height: 22px"><span class="fW600">当前选中'+(packageArr.length)+'条数据，</span>'+'确定要取消？</span>';
							}
							myjAlert.confirm({
								'content': contentTip,
								'callback':function(v){
									if(v){
										if(isBatchCancel){
											return;
										}
										isBatchCancel = true;
										var ajaxData = {
												packageIds: packageIds,
												exceptionAction: exceptionAction
										},
										$shopGroupId = $('#shopGroupId'),
										shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

										if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
										$('#loading').modal('show');
										$.ajax({
											type: "POST",
											url: 'package/batchCancelShipGoods.json',
											data: ajaxData,
											dataType: "json",
											success: function(data){
												if(data.code == 0){
													$('#cancelConfirmModal').modal('hide');
													var successList = data.bor.successList;
													var failList 	= data.bor.failList;
													batchReturnProcess(successList, failList, "订单已提交云仓，请等待审核结果！");
													refreshAjaxPage();
												}else{
													/*2017.5.17 byzym 添加URL包裹*/
													var msg = strFilterUrl(data.msg);
													$.fn.message({type: "error", msg: msg});
												}
												isBatchCancel = false;
											},
											error:function(){
												$('#loading').modal('hide');
												isBatchCancel = false;
											}
										});
									}
								}
							});
						}
					}
				});

				return;
			}

			// 如果没有选中所有页，要判断用户是否已选择订单
			var packageIds = getCheckBoxValByName("packageId");
			if(packageIds == ""){
				$.fn.message({type:"error",msg:"请至少选择一个订单"});
				return;
			}
			var exceptionAction = $("input[name='cancelActionType']:checked").val();
			if(exceptionAction != 1 && exceptionAction != 2 && exceptionAction != 3){
				$.fn.message({type: "error", msg: "请选择取消原因！"});
				return;
			}
			var packageArr = packageIds.split(",");
			var notPrintMdNum = 0;
			var isPrintpackage;
			var authId;
			for(var i=0;i<packageArr.length;i++){
				isPrintpackage = $('#printMd'+packageArr[i]);
				authId = $('#dxmAuthId'+packageArr[i]).val();
				if(isPrintpackage.length == 1 || authId == 0){
					continue;
				}
				notPrintMdNum += 1;
			}
			var contentTip = '确定要取消？';
			if(notPrintMdNum>0){
				contentTip = '<span style="line-height: 22px"><span class="fW600">当前选中'+(packageArr.length)+'条数据，</span>'+'确定要取消？</span>';
			}
			myjAlert.confirm({
				'content': contentTip,
				'callback':function(v){
					if(v){
						if(isBatchCancel){
							return;
						}
						isBatchCancel = true;
						var ajaxData = {
								packageIds: packageIds,
								exceptionAction: exceptionAction
							},
							$shopGroupId = $('#shopGroupId'),
							shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

						if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
						$('#loading').modal('show');
						$.ajax({
							type: "POST",
							url: 'package/batchCancelShipGoods.json',
							data: ajaxData,
							dataType: "json",
							success: function(data){
								if(data.code == 0){
									$('#cancelConfirmModal').modal('hide');
									var successList = data.bor.successList;
									var failList 	= data.bor.failList;
									batchReturnProcess(successList, failList, "订单已提交云仓，请等待审核结果！");
									refreshAjaxPage();
								}else{
									/*2017.5.17 byzym 添加URL包裹*/
									var msg = strFilterUrl(data.msg);
									$.fn.message({type: "error", msg: msg});
								}
								isBatchCancel = false;
							},
							error:function(){
								$('#loading').modal('hide');
								isBatchCancel = false;
							}
						});
					}
				}
			});
		}
	});
};

/** 异常订单发货 **/
var isExceptionShip = false;
var exceptionShip = function (packageId) {

	if (isExceptionShip) {
		return;
	}
	isExceptionShip = true;

	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/exceptionShipGoods.json',
		data: {
			"packageId": packageId
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「已发货」页！"});
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();
			} else {
				/*2017.5.17 byzym 添加URL包裹*/
				var msg = strFilterUrl(data.msg);
				$.fn.message({type: "error", msg: msg});
			}
			isExceptionShip = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isExceptionShip = false;
		}
	});
};

/** 批量异常订单发货 **/
var isBatchExceptionShip = false;
var batchExceptionShip = function () {
	if (isBatchExceptionShip) {
		return;
	}
	isBatchExceptionShip = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		isBatchExceptionShip = false;
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchExceptionShipGoods.json',
		data: {"packageIds": packageIds},
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
				var successList = data.bor.successList;
				var failList = data.bor.failList;
				batchReturnProcess(successList, failList, "订单已移入到「已发货」页！");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			isBatchExceptionShip = false;
		},
		error: function () {
			$('#loading').modal('hide');
			isBatchExceptionShip = false;
		}
	});
};

/***************** 扫描优化开始 ****************/
/***************** 扫描优化结束 ****************/

/** 显示重新发货弹出框 **/
var showReShip = function (packageId) {
	var $modal = $('#reShipGoodModal');
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/showReShip.htm',
		data: {"packageId": packageId},
		dataType: "html",
		success: function (data) {
            $modal.html(data);
			$('#loading').modal('hide');
            $modal.modal("hide");
            $modal.modal("show");
            $modal.find('.popoverHover').popover();
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 包裹重新发货至云仓 **/
var reSubmitYuncang = function (packageId) {
	myjAlert.confirm({
		title: '提交云仓',
		content: '主要解决原先发货仓库非云仓发货，但是货物在云仓仓库内，需要把订单推向云仓发货',
		callback: function(v) {
			if (v) {
				$('#loading').modal('show');
				$.ajax({
					type: "POST",
					url: 'package/reSubmitYuncang.json',
					data: {"packageId": packageId},
					dataType: "JSON",
					success: function (data) {
						if(data.code === 0){
							$.fn.message({type: "success", msg: "重新发货至云仓成功"});
						}else {
							$.fn.message({type: "error", msg: data.msg});
						}
						$('#loading').modal('hide');
					},
					error: function () {
						$('#loading').modal('hide');
					}
				});
			}
		}
	});
};

/** 显示重新发货提醒框 **/
var showReShipConfirm = function () {
	var orderNums = $("#reShipProductDiv").find("input[name='count']");
	var reg = /^\d+(\.\d{1,2})?$/;

	var b = validateCustom(orderNums, /^[0-9]*$/, 1, "请输入数量", "数量请输入大于0的整数");
	if (b) {
		return;
	}

	//判断邮箱是否填写
	var emailFeedOrder = $('#emailFeedOrderId').val(),
		emailVerify = /^([a-zA-Z0-9]|[\_|\.|\-])+@([a-zA-Z0-9]|[\_|\.|\-])*\.[a-zA-Z0-9]+$/;

	if (emailFeedOrder && !emailFeedOrder.match(emailVerify)) {
		$.fn.message({type: 'error', msg: '邮箱格式不正确！'});
		return;
	}

	var skus = $("#reShipProductDiv").find("input[name='productSku']");
	for (var i = 0; i < skus.length; i++) {
		var proSku = $(skus[i]).val();
		var proId = $(skus[i]).parent().find("input[name='productId']").val();

		if (proSku == '' && proId == '') {
			$.fn.message({type: "error", msg: '新增商品需要指定库存中的商品！'});
			return;
		}
	}
	$("#reShipPackageNumSpan").html($("#reShipPackageNumTd").text());
	$.ajax({
		type: "POST",
		url: 'package/isOpenPaid.json',
		data: {},
		dataType: "json",
		success: function (data) {
			var orderState = "待审核";
			if (data.code == 1) {
				orderState = "待处理"
			}
			$("#reShipStateSpan").html(orderState);
			$("#confirmReShipModal").modal("show")
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 关闭重新发货弹层 **/
var closeReShipDiv = function (hideId, showId) {
	$("#" + hideId).modal("hide");
	$("#" + showId).modal("hide").modal("show");

};

/** 执行重新发货 **/
var executeReShip = function(){
	var state = $("#reShipStateSpan").text();
	var orderNums  = $("#reShipProductDiv").find("input[name='count']");
	var prices  = $("#reShipProductDiv").find("input[name='productPrice']");
	var reg = /^\d+(\.\d{1,2})?$/;

	var b = validateCustom(orderNums,/^[1-9][0-9]*$/,1,"请输入数量","数量请输入大于0的整数");
	if(b){
		return;
	}
	var c = validateCustom(prices,reg,3,"请输入单价","单价请输入大于0的数字,小数点保留1-2位");
	if(c){
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/reShipGoods.json',
		data: $("#reShipForm").serialize(),
		dataType: "json",
		success: function (data) {

			$('#loading').modal('hide');
			$("#confirmReShipModal").modal("hide");

			if (data.code == 0) {
				$.fn.message({type: "success", msg: "订单创建成功，并移入到了「" + state + "」！"});
				$("#reShipGoodModal").modal("hide");
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();

			} else {
				$.fn.message({type: "error", msg: data.msg});
				$("#reShipGoodModal").modal("hide");
				$("#reShipGoodModal").modal("show");
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 包裹页订单详情回调 **/
var packageOrderDetaiAfter = function () {
	$("#orderDetailClose1").attr("onclick", "closePackageOrderDetail();");
	$("#orderDetailClose2").attr("onclick", "closePackageOrderDetail();");
};
/** 关闭包裹详情弹层 **/
var closePackageOrderDetail = function () {
	$("#orderDetails").modal("hide");
	$("#packageDetailModal").modal("hide");
	$("#packageDetailModal").modal("show");
};
/** 扫描包裹详情页 **/
var scanPackageDetail = function (packageId) {
	dxmPackageDetail(packageId, scanPackageDetailAfter);
};
/** 扫描包裹详情回调 **/
var scanPackageDetailAfter = function () {
	$("#packageDetailClose1").attr("onclick", "closeScanDetail();");
	$("#packageDetailClose2").attr("onclick", "closeScanDetail();");
};
/** 扫描包裹页订单详情回调 **/
var scanOrderDetaiAfter = function () {
	$("#orderDetailClose1").attr("onclick", "closeScanDetail();");
	$("#orderDetailClose2").attr("onclick", "closeScanDetail();");
};
/** 扫描发货关闭订单详情页 **/
var closeScanDetail = function () {
	$("#orderDetails").modal("hide");
	$("#packageDetailModal").modal("hide");
	$("#scanShippingModal").modal("hide");
	$("#scanShippingModal").modal("show");
	$('#scanShippingInput').focus();
};
/** 批量打印 **/
var batchPrintPackage = function (val, auId, type, call) {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	var authId = getAuthId(),
		orderField = $('#keepState').data('orderfiled'),
		isDesc = $('#keepState').data('search'),
		isCos = $('#isCos').val();

	if (isDesc == undefined || isDesc == '') {
		isDesc = "0";
	}
	if(isCos == '' || isCos == undefined){
		isCos = 0;
	}
	var url = gitWinLocHref()+"printMb.htm?authId=" + authId + "&packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc+"&isCos="+isCos;
	if (val == 1 || val == 2) {
		// 打印拣货单
		var templateId = $("#templateJhLi").attr("data-id");
		if(templateId == undefined || templateId == ''){
			templateId = '0';
		}
		if(val == 2){
			url = gitWinLocHref()+"printJhAll.htm?authId=" + authId + "&packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc+"&isAdd=1&templateId="+templateId;
		} else {
			url = gitWinLocHref()+"printJhAll.htm?authId=" + authId + "&packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc+"&templateId="+templateId;
		}
		var $shopGroupId = $('#shopGroupId'),
			shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

		if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
		if (!childPageObj) childPageObj = {};
		childPageObj[packageIds] = window.open('about:blank', '_blank');
		childPageObj[packageIds].location.href = url;
		return;
	} else {
		// 打印面单
		var smtShopId = -1;
		var agentNameType;
		var templateId;
		var comp2;
		var agentId1;
		var agentId2;
		var arr = packageIds.split(",");
		var hash = [];
		var authIdArr = [];
		if (authId == undefined || authId == '' || authId == '0' || authId == '-1') {
			for (var i = 0; i < arr.length; i++) {
				authIdArr.push($("#dxmAuthId" + arr[i]).val());
			}
			for (var i = 0; i < authIdArr.length; i++) {
				if (hash.indexOf(authIdArr[i]) == -1) {
					hash.push(authIdArr[i]);
				}
			}
			authId = $("#dxmAuthId" + arr[0]).val();
			agentNameType = $("#auth" + authId).attr("data-nametype");
			if (hash.length > 1 && (agentNameType == 22 || agentNameType == 28 || agentNameType == 170 || agentNameType == 289 || agentNameType == 326 || agentNameType == 350)) {
				for (var i = 0; i < arr.length; i++) {
					agentId1 = $("#dxmAuthId" + arr[i]).attr("data-agentid");
					if (i == 0) {
						agentId2 = agentId1;
					} else {
						if (agentId1 != agentId2 && agentNameType != 22) {
							$.fn.message({type: "error", msg: "多个物流商账号不支持批量打印。请从页面上方的「物流方式」中先选定一个物流商账号再「批量打印」！"});
							return;
						}
					}
				}
				authId = hash.join(",");
				url = gitWinLocHref() + "batchPrintMb.htm?authId=" + authId + "&packageIds=" + packageIds + "&isCos=" + isCos;
			} else {
				for (var i = 0; i < arr.length; i++) {
					comp2 = $("#dxmAuthId" + arr[i]).val();
					if (i == 0) {
						authId = comp2;
					} else {
						if (authId != comp2) {
							$.fn.message({type: "error", msg: "多个物流方式不支持批量打印。请从页面上方的「物流方式」中先选定一个物流再「批量打印」！"});
							return;
						}
					}
				}
				if (auId > -1) {
					authId = auId;
				}
				url = gitWinLocHref() + "printMb.htm?authId=" + authId + "&packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc + "&isCos=" + isCos;
				agentNameType = $("#auth" + authId).attr("data-nametype");
				templateId = $("#auth" + authId).attr("data-templateid");
			}
		} else {
			agentNameType = $("#auth" + authId).attr("data-nametype");
			templateId = $("#auth" + authId).attr("data-templateid");
		}
		if (agentNameType == 24) {
			// 这两种物流方式最多每次打印50
			if (arr.length > 50) {
				$.fn.message({type: "error", msg: "当前物流方式目前最多支持一次打印50！"});
				return;
			}
		}
		//lazada单独判断pdf的可以批量打印
		if (agentNameType == 37 || agentNameType == 357 || agentNameType == 50 ) {
			var shopId = $("#keepState").data("shopid");
			if(templateId == 25){
				var comp3 = "";
				//lazada单独判断pdf的可以批量打印
				var isLazadaPdf = false;
				if(agentNameType == 50){
					$.ajax({
						type:"post",
						url:"printMd/getPrintModel.json",
						data:{authId:authId},
						async:false,
						dataType:"json",
						success:function(data){
							if (!data.code){
								if (data.data && 'pdf' === data.data.toLowerCase()){
									isLazadaPdf = true;
								}
							}
						}
					});
				}
				for (var i = 0; i < arr.length; i++) {
					var comp2 = $("#dxmAuthId" + arr[i]).attr("data-shopid");
					if (i == 0) {
						comp3 = comp2;
					} else {
						if (comp3 != comp2 && shopId == -1) {
							if(agentNameType ==50 ){
								//lazada pdf支持多店铺打印
								if (isLazadaPdf){
									continue;
								}else{
									$.fn.message({type: "error", msg: "当前打印类型不支持多店铺同时打印，请设置打印类型为物流商PDF面单或小秘面单。<a href='"+DXM_HELP_URL+"/pre/getContent.htm?id=1904' target='_blank'>LGS多店铺打印设置方法 >></a> "});
									return;
								}
							}
							$.fn.message({type: "error", msg: "当前设置不支持多店铺打印，请先选择一个店铺。<br/><br/><a href='"+DXM_HELP_URL+"/pre/getContent.htm?id=194' target='_blank'>多店铺打印设置方法 >></a>"});
							return;
						}
					}
				}
				smtShopId = comp3;
			}
		}
	}

	var flagState = true;
	if (+agentNameType === 22) {//菜鸟打印处理
		try {
			//调用子页面的方法执行菜鸟检测和打印
			if (childPageObj && childPageObj[packageIds] && childPageObj[packageIds].closed === false && childPageObj[packageIds].BATCH_PRINT_MD &&
				childPageObj[packageIds].BATCH_PRINT_MD.caiNiaoPrintCheck && typeof childPageObj[packageIds].BATCH_PRINT_MD.caiNiaoPrintCheck === 'function') {//执行子页面的方法，在子页面显示弹层
				flagState = !childPageObj[packageIds].BATCH_PRINT_MD.caiNiaoPrintCheck(0, authId, hash.length, hash.length > 1 ? null : smtShopId);
			} else if (hash.length > 1 ? batchCheckSelectCainiao(0, authId) : checkSelectCainiao(0, authId, smtShopId)){
				// 选择了菜鸟打印
				flagState = false;
			}
			if (childPageObj && childPageObj[packageIds] && childPageObj[packageIds].closed) delete childPageObj[packageIds];//如果子页面关闭了或勾选的包裹变动了，清空该数据
		} catch (e) {
			if (hash.length > 1 ? batchCheckSelectCainiao(0, authId) : checkSelectCainiao(0, authId, smtShopId)){
				// 选择了菜鸟打印
				flagState = false;
			}
		}
	} else {
		flagState = false;
		if (type == undefined) {
			if (val == 0) {
				type = 1;
			} else if (val == 1 || val == 2) {
				type = 2;
			}
		}
		if (val != -1 && val != 2) {
			if (hash.length > 1 && (agentNameType == 22 || agentNameType == 28 || agentNameType == 170 || agentNameType == 289 || agentNameType == 326 || agentNameType == 350)) {
				if (!batchPrintCheckAuth(authId)) {
					return;
				}
				batchCheckPrint(packageIds, authId, type);
			} else {
				checkPrint(packageIds, authId, type);
			}
		}
		if (val == 0) {
            var wo = window.open('about:blank', '_blank');
            wo.location.href = url;
            $("#printedConfirmModal").modal("hide");
		} else if (val == 5) { //  val == 5 打印面单和拣货单页面调用，因为该页面打印面单被浏览器拦截，所以必须将url回调给该页面,和 val == 0 差不多，只是打印面单的方式不一样
            call && call(url);
        } else {
			if (auId == -1) {
				$("#printedConfirmBtn").attr("href", url);
			} else {
				var wo = window.open('about:blank', '_blank');
				wo.location.href = url;
			}
		}
	}
	if (flagState) {
		if (type == undefined) {
			if (val == 0) {
				type = 1;
			} else if (val == 1 || val == 2) {
				type = 2;
			}
		}
		if (val != -1 && val != 2) {
			if (hash.length > 1 && (agentNameType == 22 || agentNameType == 28 || agentNameType == 170 || agentNameType == 289 || agentNameType == 326 || agentNameType == 350)) {
				if (!batchPrintCheckAuth(authId)) {
					return;
				}
				batchCheckPrint(packageIds, authId, type);
			} else {
				checkPrint(packageIds, authId, type);
			}
		}
		if (val == 0) {
            var wo = window.open('about:blank', '_blank');
            wo.location.href = url;
            $("#printedConfirmModal").modal("hide");
		} else if (val == 5) { //  val == 5 打印面单和拣货单页面调用，因为该页面打印面单被浏览器拦截，所以必须将url回调给该页面,和 val == 0 差不多，只是打印面单的方式不一样
            call && call(url);
        } else {
			if (auId == -1) {
				$("#printedConfirmBtn").attr("href", url);
			} else {
				var wo = window.open('about:blank', '_blank');
				wo.location.href = url;
			}
		}
	}
};

//批量打印检查多个物流商渠道是否为同一物流商账号
var batchPrintCheckAuth = function (authId) {
	var b = false;
	if (authId == undefined || authId == '') {
		return b;
	}
	$.ajax({
		type: 'POST',
		url: 'order/batchPrintCheckAuth.json',
		data: {
			authId: authId
		},
		dataType: "json",
		async: false,
		success: function (data) {
			if (+data.code === -1) {
				$.fn.message({type: 'error', msg: data.msg});
			} else {
				b = true;
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	return b;
};

/*** 检测速卖通线上发货是否选择了菜鸟打印 ***/
var checkSelectCainiao = function(packageId, authId, shopId){
	var b = false;
	$.ajax({
		type: 'POST',
		url: 'cainiao/checkCainiaoAuth.json',
		data: {
            shopId: shopId,
            authId: authId,
            packageId: packageId
        },
		dataType: "json",
		async:false,
		success: function (data) {
			if(+data.code === -1){ // 未授权
				$("#cainiaoAuthModal").modal('show');
				b = true;
			} else if(+data.code === -2){
                //if(showWaveScanTwiceSortErr) showWaveScanTwiceSortErr(data.msg);
				$.fn.message({type: 'error', msg: data.msg});
				b = true;
			} else if(+data.code === 0){ // 检测是否安装菜鸟
                b = true;
				checkCainiaoPlug(function () {
                    // 显示打印列表
                    $("#cainiaoPrePrintBtn").attr("onclick","doCainiaoPrint(1,'"+ packageId +"','"+ authId +"',1);");
                    $("#cainiaoPrintBtn").attr("onclick","doCainiaoPrint(0,'"+ packageId +"','"+ authId +"',1);");
                    showCainiaoPrinters();
                });
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	return b;
};

/*** 批量打印检测速卖通线上发货是否选择了菜鸟打印 ***/
var batchCheckSelectCainiao = function (packageId, authId) {
	var b = false;
	$.ajax({
		type: 'POST',
		url: 'cainiao/batchCheckCainiaoAuth.json',
		data: {
			authId: authId
		},
		dataType: "json",
		async: false,
		success: function (data) {
			if (+data.code === -2) {
				$.fn.message({type: 'error', msg: data.msg});
				b = true;
			} else if (+data.code === 0) { // 检测是否安装菜鸟
				b = true;
				checkCainiaoPlug(function () {
					// 显示打印列表
					$("#cainiaoPrePrintBtn").attr("onclick", "doCainiaoPrint(1,'" + packageId + "','" + authId + "',1);");
					$("#cainiaoPrintBtn").attr("onclick", "doCainiaoPrint(0,'" + packageId + "','" + authId + "',1);");
					showCainiaoPrinters();
				});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	return b;
};

/** 扫描sku走菜鸟打印 **/
var scanCainiao = function(packageId, id, printMdType){
	$.ajax({
		type: "POST",
		url: 'cainiao/checkCainiaoAuth.json',
		data: {"packageId":packageId},
		dataType: "json",
		async:false,
		success: function (data) {
			if(+data.code === -1){ // 未授权
				$('#cainiaoAuthModal').modal('show');

			} else if(+data.code === -2){
                //if(showWaveScanTwiceSortErr) showWaveScanTwiceSortErr(data.msg);
				$.fn.message({type: 'error', msg: data.msg});

			} else if(+data.code === 0){
                checkCainiaoPlug(function () {
                    // 菜鸟打印
                    $("#cainiaoPid").val(packageId);
                    $("#cainiaoScanId").val(id);
                    $("#cainiaoPrintMdType").val(printMdType);
                    var printer = $("#printerSelect").val();
                    executeCainiaoPrint(0, printer, packageId, "", "", "");
                });
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 菜鸟标记为已打印 **/
var cainiaoSetPrint = function(statusList){

	var isBatch = $("#dxmPrintState").attr("data-cainiao");
	if(isBatch == 1){
		// 批量打印
		var packIds = $("#dxmPrintState").attr("data-packid").split(",");
		var len = packIds.length;
		var count = $("#dxmPrintState").attr("data-count");
		if(count == '' || count == undefined){
			count = 0;
		}
		var packArr = [];
		for(var i=0; i< statusList.length; i++){
			var status = statusList[i].status;
			var packId = statusList[i].documentID;
			var arr    = packId.split("_");
			packId     = arr[0];
			if($.inArray(packId, packArr) == -1){
				if(status == 'success'){
					voicePrompt('newMessageDIV', 'printedFlagSuccess');
					scanProgressing(4, 1);
					setPrint(packId, 2);
				} else {
					$.fn.message({type: "error", msg: "打印失败，请手动打印面单！"});
					voicePrompt('newMessageDIV', 'printFail');
				}
			}
			packArr[i] = packId;
			count++;
		}
		if(count == len){
			$("#dxmPrintState").attr("data-count", 0);
			/** 设置初始化扫描流程 **/
			clearAfterPrint();
		} else {
			$("#dxmPrintState").attr("data-count", count);
		}

	} else if(isBatch == 2){
		// 打印全部订单
		setPrintAllCainiaoResult(statusList);

	} else if(isBatch == 3){
        // 波次扫描扫描包装置为已打印
        var  packageId = $('#cainiaoPid').val();
        waveScanPackSetMdPrint(packageId,statusList);
        //防止菜鸟打印机callBack多次
        $("#cainiaoPid").val("");
        $("#cainiaoScanId").val("");
        $("#cainiaoPrintMdType").val("");
    } else if (isBatch == 4) {
        //二次分拣打印面单
        var  packageId = $('#cainiaoPid').val();
        waveTwiceSortSetMdPrint(packageId,statusList);
        //防止菜鸟打印机callBack多次
        $("#cainiaoPid").val("");
        $("#cainiaoScanId").val("");
        $("#cainiaoPrintMdType").val("");
    } else {
		// 选择了菜鸟单个打印
		var id 			= $("#cainiaoScanId").val();
		var printMdType = $("#cainiaoPrintMdType").val();
		var packageId   = $("#cainiaoPid").val();
		if(packageId > 0){
			var status = statusList[0].status;
			if(status == 'success'){
				voicePrompt('newMessageDIV', 'printedFlagSuccess');
				scanProgressing(4, 1);
				setPrint(packageId,"",printMdType);
				/** 设置初始化扫描流程 **/
				clearAfterPrint();
			} else {
				$.fn.message({type: "error", msg: "打印失败，请手动打印面单！"});
				voicePrompt('newMessageDIV', 'printFail');
			}
			$("#cainiaoPid").val("");
			$("#cainiaoScanId").val("");
			$("#cainiaoPrintMdType").val("");
		}
	}
};

/*打印拣货单pdf转html */
var batchPrintPackageHtml = function (val, auId, type,onlyJh) {

	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	var authId = getAuthId();
	var orderField = $("#keepState").data("orderfiled");
	var isDesc = $("#keepState").data("search");
	if (isDesc == undefined || isDesc == '') {
		isDesc = "0";
	}
	var isCos = $("#isCos").val();
	if(isCos == '' || isCos == undefined){
		isCos = 0;
	}
	var url = "printMb.htm?isCos="+isCos;
	if (val == 1 || val == 2) {
		if(onlyJh == 1){
			url = "printJh.htm?onlyJh=1";
		}else{
			// 打印拣货单
			url = "printJh.htm";
		}
	} else {
		// 打印面单
		var arr = packageIds.split(",");
		if (authId == undefined || authId == '' || authId == '0' || authId == '-1') {
			for (var i = 0; i < arr.length; i++) {
				var comp2 = $("#dxmAuthId" + arr[i]).val();
				if (i == 0) {
					authId = comp2;
				} else {
					if (authId != comp2) {
						$.fn.message({type: "error", msg: "多个物流方式不支持批量打印。请从页面上方的「物流方式」中先选定一个物流再「批量打印」！"});
						return;
					}
				}
			}
			if (auId > -1) {
				authId = auId;
			}
			url = "printMb.htm?isCos="+isCos;
		}
		var agentNameType = $("#auth" + authId).attr("data-nametype");
		var templateId = $("#auth" + authId).attr("data-templateid");
		if (agentNameType == 24) {
			// 这两种物流方式最多每次打印50
			if (arr.length > 50) {
				$.fn.message({type: "error", msg: "当前物流方式目前最多支持一次打印50！"});
				return;
			}
		}
		if (agentNameType == 37 || agentNameType == 22 || agentNameType == 50) {
			var shopId = $("#keepState").data("shopid");
			if(templateId == 25){
				var comp3 = "";
				for (var i = 0; i < arr.length; i++) {
					var comp2 = $("#dxmAuthId" + arr[i]).attr("data-shopid");
					if (i == 0) {
						comp3 = comp2;
					} else {
						if (comp3 != comp2 && shopId == -1) {
							$.fn.message({type: "error", msg: "当前设置不支持多店铺打印，请先选择一个店铺。<br/><br/><a href='"+DXM_HELP_URL+"/pre/getContent.htm?id=194' target='_blank'>多店铺打印设置方法 >></a>"});
							return;
						}
					}
				}
			}
		}
	}
	if (type == undefined || type == "") {
		if (val == 0) {
			type = 1;
		} else if (val == 1 || val == 2) {
			type = 2;
		}
	}
	if (val != -1 && val != 2) {
		checkPrint(packageIds, authId, type);
	}
	if (val == 0) {
		$('#isDesc').val(isDesc);
		$('#authId').val(authId);
		$('#packageIds').val(packageIds);
		$('#orderField').val(orderField);
		$('#printJhForm').attr("action",url);
		$('#printJhForm').submit();
		$("#printedConfirmModal").modal("hide");
	} else {
		if (auId == -1) {
			$("#printedConfirmBtn").attr("href", url);
		} else {
			$('#isDesc').val(isDesc);
			$('#authId').val(authId);
			$('#packageIds').val(packageIds);
			$('#orderField').val(orderField);
			$('#printJhForm').attr("action",url);
			$('#printJhForm').submit();
		}
	}
};

/** 批量打印拣货汇总单 **/
var batchPrintJhAllFlag = false;
var batchPrintJhAll = function (val) {
	if(batchPrintJhAllFlag){
		return;
	}
	batchPrintJhAllFlag = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		batchPrintJhAllFlag = false;
		return;
	}
	var authId = getAuthId();
	var orderField = $("#keepState").data("orderfiled");
	var isDesc = $("#keepState").data("search");
	if (isDesc == undefined || isDesc == '') {
		isDesc = "0";
	}
	var url = "printJhAll.htm?authId=" + authId + "&packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc;
	if (val == 2) {
		url = "printJhAllAgent.htm?authId=" + authId + "&packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc;
	} else if (val == 3) {
		url = "printJhAllPackage.htm?authId=" + authId + "&packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc;
	}
	var wo = window.open('about:blank', '_blank');
	wo.location.href = url;
	batchPrintJhAllFlag = false;
};

/** 批量打印拣货汇总单 **/
var printJhAllFlag = false;
var PrintJhAll = function (val, isOneThousand) {
	if(printJhAllFlag){
		return;
	}
	var printJhAllFlag = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		var printJhAllFlag = false;
		return;
	}
	var authId = getAuthId();
	var orderField = $("#keepState").data("orderfiled");
	var isDesc = $("#keepState").data("search");
	if (isDesc == undefined || isDesc == '') {
		isDesc = "0";
	}
	var url = "printJhAll.htm";
	if (val == 2) {
		url = "printJhAllAgent.htm";
	}else if (val == 3) {
        var storageid = $("#keepState").data("storageid");
        if (!isOneThousand) {
            isOneThousand = 0;
        }
		url = "printJhPackage.htm?isOneThousand="+isOneThousand;
        if (isOneThousand == 1) {
        	// 1000单打印必须选择一个仓库
        	if (!storageid || storageid == '0' || storageid == '-1') {
                $.fn.message({type: "error", msg: "多个仓库位置不支持混包打印。请从页面上方的「仓库位置」中先选定一个仓库再「混包打印」！"});
                return;
			}
            var paraData = getOneThousandParaData();
            authId = paraData.authId;
            url = url+'&shopId='+paraData.shopId+'&platform='+paraData.platform+'&isFree='+paraData.isFree+'&isBatch='+paraData.isBatch
                +'&storageId='+paraData.storageId+'&applyStatus='+paraData.applyStatus+'&state='+paraData.state+'&commitPlatform='+paraData.commitPlatform
                +'&applyType='+paraData.applyType+'&productStatus='+paraData.productStatus+'&startTime='+paraData.startTime+'&endTime='+paraData.endTime
                +'&custom='+paraData.custom+'&timeOut='+paraData.timeOut+'&printJh='+paraData.printJh+'&printMd='+paraData.printMd;
            var printNum = $('.determineNum').html(); // 打印的数量

            $("#printedModal").modal("show");
            $("#printSubTitle").html("拣货单");
            $("#printSpan").html("拣货单");
            $("#printSuccessSpan").html("拣货单");
            $("#successPrintNum").html(+printNum);
            $("#currentType").hide();
            $("#printedBtn").attr("onclick", "oneThousandOperator(4, 2, 1);");
			$('#printQuestionLinkGoTo').attr('href', DXM_HELP_URL + '/help/getRefreshContent.htm?id=1618');

		} else {
            var arr = packageIds.split(",");
            if (storageid == undefined || storageid == '' || storageid == '0' || storageid == '-1') {
                for (var i = 0; i < arr.length; i++) {
                    var comp2 = $("#dxmAuthId" + arr[i]).data("storageid");
                    if (i == 0) {
                        storageid = comp2;
                    } else {
                        //打印混包拣货单前校验是否在同一个仓库
                        if (storageid != comp2) {
                            $.fn.message({type: "error", msg: "多个仓库位置不支持混包打印。请从页面上方的「仓库位置」中先选定一个仓库再「混包打印」！"});
                            return;
                        }
                    }
                }
            }
            $('#packageIds').val(packageIds);
            checkPrint(packageIds,authId,2);
        }
		// 判断当前页面是否为 待审核 待处理 - 打印需加特殊字段
		var orderStatus = $('#orderStatus').val();
		if (orderStatus === 'paid' || orderStatus === 'approved') {
			url += '&checkTrack=0';
		}
	}
	var $shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (+val !== 2 && shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$('#isDesc').val(isDesc);
	$('#authId').val(authId);
	$('#orderField').val(orderField);
	$('#printJhForm').attr("action",url);
	$('#printJhForm').submit();
	var printJhAllFlag = false;
};

// 为了防止多物流搜索，如果选择多个的时候，将id清空
var getAuthId = function () {
    var authId = $("#keepState").data("authid");
    if (authId) {
		authId = authId + '';
		if (authId.indexOf(",") > -1) {
			authId = '-1';
		}
	} else {
    	authId = '-1';
	}

    return authId;
};

/** 批量打印拣货汇总单（新版） **/
var printJhFlag = false;
var PrintJhModel = function (templateId, isOneThousand) {
	if(printJhFlag){
		return;
	}
	printJhFlag = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		printJhFlag = false;
		return;
	}
	// 后台已经兼容多个搜索
	var authId = $("#keepState").data("authid");
	var orderField = $("#keepState").data("orderfiled");
	var isDesc = $("#keepState").data("search");
	if (isDesc == undefined || isDesc == '') {
		isDesc = "0";
	}
	if (!isOneThousand) {
		isOneThousand = 0;
	}
	var url = 'printJhAll.htm?templateId='+templateId+'&isOneThousand='+isOneThousand;
	if (+isOneThousand === 1) {
        var paraData = getOneThousandParaData();
		authId = paraData.authId;
		url = url+'&shopId='+paraData.shopId+'&platform='+paraData.platform+'&isFree='+paraData.isFree+'&isBatch='+paraData.isBatch
		+'&storageId='+paraData.storageId+'&applyStatus='+paraData.applyStatus+'&state='+paraData.state+'&commitPlatform='+paraData.commitPlatform
		+'&applyType='+paraData.applyType+'&productStatus='+paraData.productStatus+'&startTime='+paraData.startTime+'&endTime='+paraData.endTime
		+'&custom='+paraData.custom+'&timeOut='+paraData.timeOut+'&printJh='+paraData.printJh+'&printMd='+paraData.printMd;
		if (paraData.shopGroupId) url += '&shopGroupId=' + paraData.shopGroupId;
		var printNum = $('.determineNum').html();

		$("#printedModal").modal("show");
		$("#printSubTitle").html("拣货单");
		$("#printSpan").html("拣货单");
		$("#printSuccessSpan").html("拣货单");
		$("#successPrintNum").html(+printNum);
		$("#currentType").hide();
		$("#printedBtn").attr("onclick", "oneThousandOperator(4, 2, 1);");
		$('#printQuestionLinkGoTo').attr('href', DXM_HELP_URL + '/help/getRefreshContent.htm?id=1618');

    } else {
		$('#packageIds').val(packageIds);
		setTimeout(function () {
			checkPrint(packageIds,authId,2);
		},1000);
		var $shopGroupId = $('#shopGroupId'),
			shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

		if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	}
	// 判断当前页面是否为 待审核 待处理 - 打印需加特殊字段
	var orderStatus = $('#orderStatus').val();
	if (orderStatus === 'paid' || orderStatus === 'approved') {
		url += '&checkTrack=0';
	}

	$('#isDesc').val(isDesc);
	$('#authId').val(authId);
	$('#orderField').val(orderField);
    $('#printJhForm').attr("action",url);
    $('#printJhForm').submit();
	printJhFlag = false;
};

/** 打印全部（面单+拣货） **/
var printConfirm = function () {
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds === "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	var b = true;
	var arr = packageIds.split(",");
	var authId = -1;
	for (var i = 0; i < arr.length; i++) {
		var comp2 = $("#dxmAuthId" + arr[i]).val();
		if (i == 0) {
			authId = comp2;
		} else {
			if (authId != comp2) {
				$.fn.message({type: "error", msg: "多个物流方式不支持批量打印。请从页面上方的「物流方式」中先选定一个物流再「批量打印面单+拣货单」！"});
				b = false;
				return;
			}
		}
	}
	if (!b) {
		return;
	}
	batchPrintPackage(2, -1, 0);
};

/** 打印税单 **/
var batchInvoice = function () {
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个lazada订单"});
		return;
	}

	var orderField = $("#keepState").data("orderfiled");
	var isDesc = 0;
	var state = $("#keepState").data("state");
	if (state == 'shipped') {
		isDesc = 1;
	}

	var url = "printLzdInvoice.htm?packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc;
	checkLzdPrint(packageIds);

	var wo = window.open('about:blank', '_blank');
	wo.location.href = url;
};
/**批量标记打印状态**/
var batchSignPackage = function (val,isPrint, auId, type) {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	var authId = getAuthId();
	if (type == undefined) {//type: 1 面单 2 拣货单
		if (val == 0) {
			type = 1;
		} else if (val == 1 ) {
			type = 2;
		}
	}

	if (val != -1 && val != 2) {
		checkSign(packageIds, authId, type,isPrint);
	}
};
/** 检查lazada税单打印状态 **/
var checkLzdPrint = function (packageId) {

	$("#printedLzdModal").modal("show");
	$.ajax({
		type: "POST",
		url: 'checkLzdPrint.json',
		data: {"packageIds": packageId},
		dataType: "json",
		success: function (data) {
			$("#successPrintLzdNum").html(data.success);
			$("#errorPrintLzdNum").html(data.fail);

			var str = "";
			var failList = data.bor.failList;
			for (var i = 0; i < failList.length; i++) {
				var obj = failList[i];
				str += "包裹为「 <b class='fRed f16'>" + obj.id + " </b>」打印失败，原因<b class='fRed'>" + obj.msg + "</b><br/>";
			}
			$("#errorLzdInfo").html(str);
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

//打印速卖通全托管拣货单
$(document).on('click', '.parentA', function(event) {
	event.stopPropagation();
	batchPrintAliChoiceLabel(1);
});
$(document).on('click', '.inotDoSpan', function(event) {
	event.stopPropagation();
});
$(document).on('click', '.getContentBtn', function(event) {
	event.stopPropagation();
	var wo = window.open('about:blank', '_blank');
	wo.location.href =  DXM_HELP_URL + '/pre/getContent.htm?id=2656';
});
var batchPrintAliChoiceLabel = function (type, isOldLink) {
	var packageIds = '',
		semiTrusteeship = false, // 半托管
		fullyManaged = false, // 全托管
		authIdArr = [],
		platformArr = [];
	$('input[name="packageId"]:checked').each(function(){
		var $this = $(this),
			val = $this.val(),
			$dxmAuthIdInput = $('#dxmAuthId' + val),
			curAuthId = $dxmAuthIdInput.val(),
			globalCollection = $dxmAuthIdInput.attr('data-globalcollection'),
			curPlatform = $dxmAuthIdInput.attr('data-platform');

		if (!authIdArr.length || authIdArr.indexOf(curAuthId) === -1) {
			authIdArr.push(curAuthId);
		}

		if (!platformArr.length || platformArr.indexOf(curPlatform) === -1) {
			platformArr.push(curPlatform);
		}

		// 当前订单是 速卖通全托管 还是 半托管
		if (globalCollection === '8') {
			semiTrusteeship = true; // 半托管
		} else {
			fullyManaged = false; // 全托管
		}

		packageIds += packageIds ? ',' + val : val;
	});
	if (!packageIds) {
		$.fn.message({type: 'error', msg: '请至少选择一个订单'});
		return;
	}

	if(authIdArr.length > 1) {
		$.fn.message({type: 'error', msg: '多个物流方式不支持批量打印'});
		return;
	}

	if(platformArr.length > 1) {
		$.fn.message({type: 'error', msg: '多个平台渠道不支持打印'});
		return;
	}
	// lazada全托管 或者 速卖通全托管
	if(platformArr.join(',') !== 'lzdChoice' && platformArr.join(',') !== 'aliChoice') {
		$.fn.message({type: 'error', msg: '非全托管平台不支持打印'});
		return;
	}

	if (semiTrusteeship && fullyManaged) {
		$.fn.message({type: 'error', msg: '全托管和半托管店铺暂不支持同时打印标签'});
		return;
	}

	// var url = gitWinLocHref() + 'printChoiceItemBarcode.htm?packageIds=' + packageIds + '&type=' + type + '&authId=' + authIdArr.join(',');
	// window.open(url);

	var wo = window.open('about:blank', '_blank'),
		url = !!isOldLink ? 'printChoiceItemBarcode.json' : 'printChoiceItemBarcodeNew.json'; // 旧的按钮使用老链接26号上线时删除
	MYJ.ajax({
		type: 'GET',
		url: url,
		pointKey: 'printChoiceItemBarcodeNew',
		async: false,
		data: {
			platform: platformArr.join(','),
			type: type,
			uid: $('#userPuid').val(),
			packageIds: packageIds,
			authId: authIdArr.join(',')
		},
		success: function(res) {
			if (!res.code) {
				wo.location.href = res.data.pdfUrl;
			} else {
				wo.close();
				$.fn.message({type: 'error', msg: res.msg});
			}
		}
	})
};

/** 打印发票 **/
var batchPrintInvoice = function () {
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	checkPrintInvoice(packageIds);
};

/** 检查发票打印状态 **/
var checkPrintInvoice = function (packageIds) {
	var orderField = $("#keepState").data("orderfiled");
	var isDesc = 0;
	var state = $("#keepState").data("state");
	if (state == 'shipped') {
		isDesc = 1;
	}
	$.ajax({
		type: "POST",
		url: 'checkPrintInvoice.json',
		data: {"packageIds": packageIds},
		dataType: "json",
		success: function (data) {
			if (data.code == -1) {
				$("#errorInvoiceInfo").html(data.msg);
				$("#printedInvoiceModal").modal("show");
			} else {
				var url = "printInvoice.htm?packageIds=" + packageIds + "&orderField=" + orderField + "&isDesc=" + isDesc;
				var wo = window.open('about:blank', '_blank');
				wo.location.href = url;
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 置为已打印 **/
var batchSetPrint = function (packageIds, authId, type,isPrint) {
	// 多品混包 自动扫描包裹 手动打印后重置 搜索
	var scanPackType = $('#scanPackType').val();
	if (+scanPackType === 3) {
		$("#scanSkuCheckInput").attr("onkeydown", "showPrintWaveScan(event, 1);");
		$("#scanPackBtn").attr("onclick", "printWaveValidate();");
	}

	$('#signedModal').modal('hide');
	$('#printedModal').modal('hide');
	if(isNaN(isPrint)) {
		isPrint=1;//默认设置为已打印
	}
	var ajaxData = {
		packageIds: packageIds,
		type: type,
		authId: authId,
		isPrint: isPrint
	},
	$shopGroupId = $('#shopGroupId'),
	shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
    $('#loading').modal('show');
	$.ajax({
		type: 'POST',
		url: 'package/batchSetPrint.json',
		data: ajaxData,
		dataType: 'json',
		success: function (data) {
            $('#loading').modal('hide');
			var print = '已打印';
			if(isPrint == 0){
				print = '未打印';
			}
			var successList = data.bor.successList;
			var failList 	= data.bor.failList;
			batchReturnProcess(successList, failList, "符合条件的订单已标记为" + print);
			// 是否来自多品分拣
			var skusSortingOpt = $('#skusSortingOpt').val();
			//是否来自波次详情
            var $waveId = $('#waveId').val();
            //是否来自波次查询包裹
            var $fromWavePackage = $('#fromWavePackage').val();
            //是否来自包裹详情
            var $wavePackageId = $('#wavePackageId').val();
            //是否来自异常包裹打印
			var $fromWaveExceptPackage = $('#fromWaveExceptPackage').val();
			//是否来自扫描包装页
			var $fromWaveScanPackage = $('#fromWaveScanPackage').val();
            if ($waveId != undefined && $waveId != null && +$waveId > 0 && !$fromWaveScanPackage) {
                if (packageIds.indexOf(',') > 0) {
                    //批量置为已打印
                    waveDetail.batchSetDetailPrint(packageIds, $waveId);
                } else {
                	var twiceSortPrintMd = $('#twiceSortPrintMd').val();
                    if(twiceSortPrintMd != undefined && twiceSortPrintMd != null && +twiceSortPrintMd > 0){
                        //二次分拣手动标记打印
                        setDetailPrint(packageIds, $waveId, 5);
                    } else {
                        //波次详情单个置为已打印
                        setDetailPrint(packageIds, $waveId, 1);
                    }
                }
            } else if ($fromWavePackage != undefined && $fromWavePackage != null && +$fromWavePackage == 1) {
                setDetailPrint(packageIds,$waveId, 2);
            } else if ($wavePackageId != undefined && $wavePackageId != null && +$wavePackageId > 0) {
                setDetailPrint(packageIds,$waveId, 3);
            } else if ($fromWaveExceptPackage != undefined && $fromWaveExceptPackage != null && +$fromWaveExceptPackage == 1) {
                packageWave.pageList();
            } else if ($fromWaveScanPackage != undefined && $fromWaveScanPackage != null && +$fromWaveScanPackage == 1) {
                setDetailPrint(packageIds,$waveId, 4);
            } else if(+skusSortingOpt){
                pickingConfirmPrinted(packageIds);
			} else {
				if (+($('#isRefreshPage').val()) === 1){//波次快进快出详情页的面单打印，刷新整个页面
					setTimeout(function () {
						window.location.reload();
					}, 500);
				} else if ($("#groupKeepState").data("ordergroupmodule") != 1) {
                    refreshAjaxPage();
                } else {
                    groupOrderList();
                }
            }
		},
		error: function () {
			$.fn.message({type: 'error', msg: '网络超时，请稍后重试！'});
			$('#loading').modal('hide');
		}
	});
};

//扫描包装全部打印完成
$(document).off('keydown', '#waveScanFinishModal');
$(document).on('keydown', '#waveScanFinishModal', function (e) {
	var key = window.event ? e.keyCode : e.which;
	if (key.toString() == "13") {
		$("#waveScanFinishModal").modal("hide");
		//跳到扫描包装列表页
		window.onbeforeunload = null;
		window.location.href = gitWinLocHref() + 'dxmWave/index.htm?indexType=3';
	}
});

$(document).off('keydown', '#scanPackCompletesModal');
$(document).on('keydown', '#scanPackCompletesModal', function (e) {
	var key = window.event ? e.keyCode : e.which;
	if (+key === 13) {
		$('#scanPackCompletesModal').modal('hide');
	}
});

/** 设置波次订单打印状态 **/
var setDetailPrint = function(packageId, waveId, fromType){
	// fromType 1、波次详情 2、包裹列表 3、包裹详情 4、扫描包装页 5、二次分拣手动标记打印
	var isNextPackage = $('#isNextPackage').val();//等于1进行递归执行
	if(waveId == undefined || waveId == null || waveId == ''){
		waveId = '0';
	}
	if(+fromType !== 5){
		window.onbeforeunload = null; //去除刷新拦截
	}
    $('#loading').modal('show');
    $.ajax({
        type: "POST",
        url: 'dxmWave/setDetailPrint.json',
        data: {
        	packageId: packageId,
			waveId: waveId
		},
        dataType: "json",
        success: function (data) {
            $('#loading').modal('hide');
            if (data.code == 0) {
                if (fromType == 1) {
                    var wo = window.open('about:blank', '_self');
                    wo.location.href = gitWinLocHref() + "dxmWave/waveDetail.htm?waveId=" + waveId;
                } else if (fromType == 2) {
                    packageWave.pageList();
                } else if (fromType == 3) {
                    var wo = window.open('about:blank', '_self');
                    wo.location.href = gitWinLocHref() + 'package/wavePackDetail.htm?packageId=' + packageId;
                } else if (fromType == 4) {
                    //判断扫描包装一体化开启情况
                    if (waveScanPackWeightVal == 1) {
                        //开启称重
						//标记已打印
						scanWavePackSetPrintAddScanedCount(packageId);
                        var $packId = $('#packageCheckId').val();
                        if (packageId === $packId) {
                            //光标移入称重、SKU输入框disabled、查询按钮绑定称重事件
                            $('#elecScanPackWeightInput').focus().select();
                            $('#scanSkuCheckInput').prop('disabled', true);
                            $("#scanPackBtn").attr("onclick", "waveScanPackUnity.scanWavePackWeightSearch();");
						} else {
                            $('#scanSkuCheckInput').prop('disabled', false);
                            $('#elecScanPackWeightInput').val('');
                            $('#scanSkuCheckInput').val('');
                            $('#scanSkuCheckInput').focus().select();
						}
                        if (+data.res === -1) {
                            isFinishScanPack = 1;
                        }
                    } else if (waveScanPackShipVal == 1) {
                    	//开启出库
                        //标记已打印
                        scanWavePackSetPrintAddScanedCount(packageId);
                        //开启出库
                        waveScanPackUnity.scanWavePackOutStorage(packageId);
                        if (+data.res === -1) {
                            //结束作业弹层提示
                            $('#scanPackCompletesModal').modal('show');

							//判断是否开启单数还是多数
							var singleModelDataID = $('#singleModelDataID').length;
							if (singleModelDataID) {
								dataClearMethod(packageId, 1);
							}
                        }else{
							//判断是否开启单数还是多数
							var singleModelDataID = $('#singleModelDataID').length;

							if (singleModelDataID) {
								$('#printWaveDivT').html('');
								$('.noConInfoBox').removeClass('hide');
								//判断是否批量自动打印
								if (+isNextPackage === 1) {
									easyModelPackageCheckSkuQuery(singleDataCode, isNextPackage);
								}
							}
						}
                    } else {
                        //未开启一体化
                        if (-1 == data.res) {
                            $('#scanPackCompletesModal').modal('show');

							//判断是否开启单数还是多数
							var singleModelDataID = $('#singleModelDataID').length;
							if (singleModelDataID) {
								dataClearMethod(packageId);
							}
                        } else {
                        	//判断是否开启单数还是多数
							var singleModelDataID = $('#singleModelDataID').length;
							if (singleModelDataID) {
								dataClearMethod(packageId);
								//判断是否批量自动打印
								if (+isNextPackage === 1) {
									easyModelPackageCheckSkuQuery(singleDataCode, isNextPackage);
								}
							} else {
								window.location.href = gitWinLocHref() + 'dxmWave/index.htm?indexType=3';
							}
                        }
                    }
                } else if (fromType == 5) {
                    var $packageBox = $("#packageListConTable").find('.packageBox[data-packid='+ packageId + ']');
                    $packageBox.attr('data-isprintmd','1');
                    $packageBox.find('div.mdClass').removeClass('print-going').removeClass('hide').removeClass('print-not');
                    $packageBox.find('div.mdClass').find('.unPrintMd').removeClass('hide');

                    //手动打印，打印成功--生成分拣记录
					var trackNum = $packageBox.attr('data-trackNum');
					var recordsData = {
						type: 'print',
						val: [{
							type: 'success',
							num: $packageBox.attr('data-boxNum'),
							info: ['【'+$packageBox.find('.packageBoxLabelCheck').html()+'】打印成功', trackNum ? '「'+trackNum+'」' : '']
						}]
					};
					//生成单个sku分拣记录
					generatingSortingRecords(recordsData);
                }
            } else {
                $.fn.message({type: "error", msg: data.msg});
            }
        },
        error: function () {
            $('#loading').modal('hide');
        }
    });
};

/** 数据还原清空 **/
var dataClearMethod = function (packageId, type) {
	$('#printWaveDivT').html('');
	$('.noConInfoBox').removeClass('hide');
	var processCount = parseInt($('#waveProcessingSpan').text()),
		printMdTr = $("#scanPackingTBody").find("tr[data-id='" + packageId + "']");
	//获取缓存中的订单-存在记录的话更新下面单打印时间
	printMdTr.find('.signUnPrint').removeClass('hide');
	var mdTimeStr = getNowFormatDate();
	$('#scanPackPrintMd_' + packageId).html('面单打印：' + mdTimeStr);
	printMdTr.find(".printMd").attr("data-original-title", "已打印面单<br/>"+mdTimeStr).removeClass('f-red').addClass('f-green-new');
    //过滤掉开启出库数量
	if(+type !== 1){
		$('#waveProcessingSpan').text(processCount + 1);
	}
}

/** 波次扫描包装一体化 手动标记已打印进度+1 **/
var scanWavePackSetPrintAddScanedCount = function (packageId) {
    var $scanPackingTBody = $('#scanPackingTBody');
    var printTr = $scanPackingTBody.find("tr[data-id='" + packageId + "']");
    if (printTr.length == 0) {
        //添加打印面单记录
        if ($scanPackingTBody.find('.contentEmptyInfo').length > 0) {
            $scanPackingTBody.find('.contentEmptyInfo').remove();
        }
        var len = $scanPackingTBody.find("tr").length;
        len = len + 1;
        var packStr = getPrintedPackStr(packageId, len, 1);
        $scanPackingTBody.prepend(packStr);
    } else {
        //存在记录的话更新下面单打印时间
        var mdTimeStr = getNowFormatDate();
        $('#scanPackPrintMd_' + packageId).html('面单打印：' + mdTimeStr);
        var $printMd = $('#prindMdRecord_' + packageId);
        $printMd.removeClass("f-red").removeClass("gray-a").addClass("f-green-new");
        $printMd.attr("data-original-title", "已打印面单<br/>"+mdTimeStr);
        printTr.find('.signUnPrint').removeClass('hide');
	}
    //把当前包装的包裹标记已打印
    $('#prindMdRecord_' + packageId).removeClass("f-red").removeClass("gray-a").addClass("f-green-new");

    //同包裹且未标记已打印 进度加1
    var $packId = $('#packageCheckId').val();
    var $packPrintMd = $('#packPrintMd').val();
    if (packageId === $packId && $packPrintMd && +$packPrintMd == 0) {
        $('#packPrintMd').val('1');
        var processCount = parseInt($("#waveProcessingSpan").text());
        processCount++;
        $("#waveProcessingSpan").text(processCount + '');
        //防止在生成打印记录的时候用户点击查询把包裹信息清掉
        $('#isWavePrintMdIng').val('0');
        if ($('#printWaveDivT').find('tr').length === 0) {
            $('.noConInfoBox').removeClass('hide');
        } else {
            $('.noConInfoBox').addClass('hide');
        }
    }
};


/** 置为已打印 **/
var setPrint = function (packageId, val, printMdType, call) {
	$.ajax({
		type: "POST",
		url: 'package/setPrint.json',
		data: {"packageId": packageId,"printMdType":printMdType},
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
                $.fn.message({type: "success", msg: "成功标记为已打印！"});
                //是否来自波次详情
                var $waveId = $('#waveId').val();
                //是否来自波次查询包裹
                var $fromWavePackage = $('#fromWavePackage').val();
                //是否来自包裹详情
                var $wavePackageId = $('#wavePackageId').val();
                //是否来自异常包裹打印
                var $fromWaveExceptPackage = $('#fromWaveExceptPackage').val();
                //是否来自扫描包装页
                var $fromWaveScanPackage = $('#fromWaveScanPackage').val();
				//是否来自多品分拣
				var $fromBatchTranscript = $('#fromBatchTranscript').val();
                if ($waveId != undefined && $waveId != null && +$waveId > 0 && !$fromWaveScanPackage) {
                    if (packageIds.indexOf(',') > 0) {
                        //批量置为已打印
                        waveDetail.batchSetDetailPrint(packageIds, $waveId);
                    } else {
                        var twiceSortPrintMd = $('#twiceSortPrintMd').val();
                        if(twiceSortPrintMd != undefined && twiceSortPrintMd != null && +twiceSortPrintMd > 0){
                            //二次分拣手动标记打印
                            setDetailPrint(packageIds, $waveId, 5);
                        } else {
                            //波次详情单个置为已打印
                            setDetailPrint(packageIds, $waveId, 1);
                        }
                    }
                } else if ($fromWavePackage != undefined && $fromWavePackage != null && +$fromWavePackage == 1) {
                    setDetailPrint(packageIds,$waveId, 2);
                } else if ($wavePackageId != undefined && $wavePackageId != null && +$wavePackageId > 0) {
                    setDetailPrint(packageIds,$waveId, 3);
                } else if ($fromWaveExceptPackage != undefined && $fromWaveExceptPackage != null && +$fromWaveExceptPackage == 1) {
                    packageWave.pageList();
                }else if ($fromWaveScanPackage != undefined && $fromWaveScanPackage != null && +$fromWaveScanPackage == 1) {
                    setDetailPrint(packageIds,$waveId, 4);
				}else if ($fromBatchTranscript != undefined && $fromBatchTranscript != null && +$fromBatchTranscript == 1) {
					var isCheck = $('#printBatchCheck1').prop('checked'),
						$packageBox = null;
					if (isCheck) {
						$packageBox = $('#scanIdentificaBoxTable').find('.packageBoxBac[data-packid="'+packageId+'"]').parent();
					} else {
						$packageBox = $('#packageListConTable').find('.packageBox[data-packid="'+packageId+'"]');
					}
					$packageBox.attr('data-isprint', '1');
					$packageBox.find('.triangular').removeClass('red').addClass('green');
					$('#printBatchNumSku').prop('disabled', false).focus();
                } else {
                    // 标记打印状态
                    $("#printBatchDivT").find("tr[data-id='"+ packageId +"']").find(".printState").removeClass("fColor2").addClass("fColor9");
                    $('#scanSkuProDiv').find('p:nth-child(4)').css('background-position', '100.2% -32px');
                    $('#scanSkuProDiv').find('p:nth-child(5)').addClass('goOn').css('background-position', '100.2% -160px');
                }
			} else {
				$.fn.message({type: "error", msg: data.msg});
				$("#printBatchDivT").find("tr[data-id='"+ packageId +"']").find(".printState").removeClass("fColor2").addClass("fColor5");
			}

			var proCount = parseInt($("#printBatchCountSpan").text());
			if(isNaN(proCount)){
				proCount = 0;
			}
			$("#printBatchCountSpan").text(proCount+1);

			//执行回调
			call && typeof call === 'function' && call();
		},
		error: function () {
			$('#loading').modal('hide');

			//执行回调
			call && typeof call === 'function' && call();
		}
	});
};

/** 检查打印状态 **/
var checkPrint = function (packageId, authId, type, isScan) {
	var $errorInfo = $('#errorInfo'),
		$successPrintNum = $('#successPrintNum'),
		$errorPrintNum = $('#errorPrintNum');

	if (authId && authId.indexOf(',') > -1) {
		authId = '-1';
	}
	if (packageId === undefined) packageId = '';//处理参数为undefined时报语法错误的问题
	if (authId === undefined) authId = '';
	if(isScan == 1){
		$("#printedBtn").attr("onclick", "setPrint('" + packageId + "',2,0);");
	} else {
		$("#printedBtn").attr("onclick", "batchSetPrint('" + packageId + "','" + authId + "'," + type + ");");
	}
	$errorInfo.html('');
	$successPrintNum.html(0);
	$errorPrintNum.html(0);
	if (type == 2) {
		$("#printedModal").modal("show");
		var arr = packageId.split(",");
		$("#printSubTitle").html("拣货单");
		$("#printSpan").html("拣货单");
		$("#printSuccessSpan").html("拣货单");
		$successPrintNum.html(arr.length);
		$("#currentType").hide();
		$('#printQuestionLinkGoTo').attr('href', DXM_HELP_URL + '/help/getRefreshContent.htm?id=1618');
	} else {
		$.ajax({
			type: "POST",
			url: 'checkPrint.json',
			data: {"packageIds": packageId, "authId": authId},
			dataType: "json",
			success: function (data) {
				if (data.code == -1) {
					/** 选择了平台的物流方式 **/
					$("#printedPlatformModal").modal("show");
				} else if (data.code == -2) {
					/** 物流方式未授权 **/
					$.fn.message({type: "error", msg: data.msg});
				} else {
					$("#printedModal").modal("show");
                    $("#currentType").show();
					$successPrintNum.html(data.success);
					$errorPrintNum.html(data.fail);
                    $("#printMbFormatsType").html(data.printMbFormats);
                    if (data.printFormat && data.printFormat != '') {
                        $("#printFormat").html('「' + data.printFormat + '」');
                    }
					$("#gotoApAuthDetail").removeClass('hide');
                    $("#gotoApAuthDetail").attr('href','providerAuth/editSetIndex.htm?apAuthId='+data.authId+'&fromOrder=1');
					var str = "";
					var failList = data.bor.failList;
					for (var i = 0; i < failList.length; i++) {
						var obj = failList[i];
						str += "包裹为「 <b class='fRed f16'>" + obj.id + " </b>」打印失败，原因<b class='fRed'>" + obj.msg + "</b><br/>";
					}
					$errorInfo.html(str);
					if (type == 1) {
						$("#printSubTitle").html("面单");
						$("#printSpan").html("面单");
						$("#printSuccessSpan").html("面单");
					} else {
						$("#printSpan").html("面单拣货单");
						$("#printSuccessSpan").html('面单拣货单');
					}
					$('#printQuestionLinkGoTo').attr('href', DXM_HELP_URL + '/help/getRefreshContent.htm?id=' + (+type === 1 ? '535' : '1618'));//根据类型链接跳转的地址
				}
			},
			error: function () {
				$('#loading').modal('hide');
			}
		});
	}
};

/** 批量检查打印状态 **/
var batchCheckPrint = function (packageId, authId, type) {
	$("#printedBtn").attr("onclick", "batchSetPrint('" + packageId + "','" + -1 + "'," + type + ");");
	$.ajax({
		type: "POST",
		url: 'batchCheckPrint.json',
		data: {"packageIds": packageId, "authId": authId},
		dataType: "json",
		success: function (data) {
			if (data.code == -1) {
				/** 选择了平台的物流方式 **/
				$("#printedPlatformModal").modal("show");
			} else if (data.code == -2) {
				/** 物流方式未授权 **/
				$.fn.message({type: "error", msg: data.msg});
			} else {
				$("#printedModal").modal("show");
				$("#currentType").show();
				$("#successPrintNum").html(data.success);
				$("#errorPrintNum").html(data.fail);
				$("#printMbFormatsType").html(data.printMbFormats);
				if (data.printFormat && data.printFormat != '') {
					$("#printFormat").html('「' + data.printFormat + '」');
				}
				$("#gotoApAuthDetail").addClass('hide');
				var str = "";
				var failList = data.bor.failList;
				for (var i = 0; i < failList.length; i++) {
					var obj = failList[i];
					str += "包裹为「 <b class='fRed f16'>" + obj.id + " </b>」打印失败，原因<b class='fRed'>" + obj.msg + "</b><br/>";
				}
				$("#errorInfo").html(str);
				if (type == 1) {
					$("#printSubTitle").html("面单");
					$("#printSpan").html("面单");
					$("#printSuccessSpan").html("面单");
				} else {
					$("#printSpan").html("面单拣货单");
					$("#printSuccessSpan").html("面单拣货单");
				}
				$('#printQuestionLinkGoTo').attr('href', DXM_HELP_URL + '/help/getRefreshContent.htm?id=' + (+type === 1 ? '535' : '1618'));//根据类型链接跳转的地址
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};
/**检查标记状态**/
var checkSign = function (packageId, authId, type, isPrint, val, isOneThousand) {
	if(isOneThousand == 1){
		$("#signedBtn").attr("onclick", "oneThousandOperator("+ val + "," + type +","+isPrint+");");
	} else {
		$("#signedBtn").attr("onclick", "batchSetPrint('" + packageId + "','" + authId + "','" + type +"','"+isPrint+"');");
	}
	if (type == 1 && isPrint==1) {//面单 标记打印
		$("#signedModal").modal("show");
		$("#signSpan").html("面单");
		$("#signStateSpan").html("「已打印」");
		$("#signedBtn").html("标记为已打印");
	} else if(type==2 && isPrint==1){ //拣货单 标记打印
		$("#signedModal").modal("show");
		//var arr = packageId.split(",");
		$("#signSpan").html("拣货单");
		$("#signStateSpan").html("「已打印」");
		$("#signedBtn").html("标记为已打印");
	}else if(type==1 && isPrint==0) { //面单 标记未打印
		$("#signedModal").modal("show");
		$("#signSpan").html("面单");
		$("#signStateSpan").html("「未打印」");
		$("#signedBtn").html("标记为未打印");
	}else if(type==2 && isPrint==0) {  //拣货单 标记未打印
		$("#signedModal").modal("show");
		$("#signSpan").html("拣货单");
		$("#signStateSpan").html("「未打印」");
		$("#signedBtn").html("标记为未打印");
	}
};
/** 发货  **/
var isShipGoods = false;
var shipGoods = function (packageId) {
	if (isShipGoods) {
		return;
	}
	isShipGoods = true;
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/shipGoods.json',
		data: {"packageId": packageId},
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "操作成功！订单已经移入「已交运」"});
				$("#packageDetailModal").modal("hide");
			} else {
				/*2017.5.17 byzym 添加URL包裹*/
				var msg = strFilterUrl(data.msg);
				$.fn.message({type: "error", msg: msg});
			}
			$('#loading').modal('hide');
			isShipGoods = false;
			refreshAjaxPage();
		},
		error: function () {
			$('#loading').modal('hide');
			isShipGoods = false;
		}
	});
};

/** 取消发货  **/
var cancelShip = false;
var cancelShipGoods = function (packageId) {
	$('#loading').modal('show');
	$.ajax({
	    url: 'package/checkIsWaving.json',
	    type: 'get',
		data: {packageIds: packageId},
	    dataType: 'json',
	    success: function(data) {
	        $('#loading').modal('hide');
	        if (data.code) {
				myjAlert.confirm({
					content: data.msg + "确认取消吗？",
					callback: function(v){
						if(v){
							if (cancelShip) {
								return;
							}
							cancelShip = true;
							var exceptionAction = $("input[name='cancelActionType']:checked").val();
							if(exceptionAction != 1 && exceptionAction != 2 && exceptionAction != 3){
								$.fn.message({type: "error", msg: "请选择取消原因！"});
								cancelShip = false;
								return;
							}

							$('#loading').modal('show');
							$.ajax({
								type: "POST",
								url: 'package/cancelShipGoods.json',
								data: {"packageId": packageId, "exceptionAction": exceptionAction},
								dataType: "json",
								success: function (data) {
									if (data.code == 0) {
										$('#cancelConfirmModal').modal('hide');
										$.fn.message({type: "success", msg: "订单正在取消中，请等待审核结果"});
										$("#packageDetailModal").modal("hide");
										refreshAjaxPage();
									} else {
										/*2017.5.17 byzym 添加URL包裹*/
										var msg = strFilterUrl(data.msg);
										$.fn.message({type: "error", msg: msg});
									}
									$('#loading').modal('hide');
									cancelShip = false;
								},
								error: function () {
									$('#loading').modal('hide');
									cancelShip = false;
								}
							});
						}
					}
				})

				return;
			}

			if (cancelShip) {
				return;
			}
			cancelShip = true;
			var exceptionAction = $("input[name='cancelActionType']:checked").val();
			if(exceptionAction != 1 && exceptionAction != 2 && exceptionAction != 3){
				$.fn.message({type: "error", msg: "请选择取消原因！"});
				cancelShip = false;
				return;
			}

			$('#loading').modal('show');
			$.ajax({
				type: "POST",
				url: 'package/cancelShipGoods.json',
				data: {"packageId": packageId, "exceptionAction": exceptionAction},
				dataType: "json",
				success: function (data) {
					if (data.code == 0) {
						$('#cancelConfirmModal').modal('hide');
						$.fn.message({type: "success", msg: "订单正在取消中，请等待审核结果"});
						$("#packageDetailModal").modal("hide");
						refreshAjaxPage();
					} else {
						/*2017.5.17 byzym 添加URL包裹*/
						var msg = strFilterUrl(data.msg);
						$.fn.message({type: "error", msg: msg});
					}
					$('#loading').modal('hide');
					cancelShip = false;
				},
				error: function () {
					$('#loading').modal('hide');
					cancelShip = false;
				}
			});
	    }
	});
};

/** 包裹详情页显示作废包裹确认框 **/
var showInvalidPackage = function (val) {
	if(val == 1){
		$("#invalidPackageOverseaSpan").css("display", "");
	} else {
		$("#invalidPackageOverseaSpan").css("display", "none");
	}
	$("#invalidPackageModal").modal("show");
};

/** 批量打回待处理 **/
var showBatchInvalid = function (val) {
	var packageIds = getCheckBoxValByName('packageId'),
		orderIsYuncang = $('#orderIsYuncang').val(), //是否是云仓
		$modal = $('#batchInvalidPackageModal');

	if (packageIds === '') {
		$.fn.message({type: 'error', msg: '请至少选择一个订单！'});
		return;
	}

	if(+val === 1 && orderIsYuncang !== 'true'){
		$modal.find('#batchInvalidPackageOverseaSpan').css('display', '');
	} else {
		$modal.find('#batchInvalidPackageOverseaSpan').css('display', 'none');
	}
	$modal.find('.determineBtn').attr('onclick', 'batchInvalidPackage();');	// 非组操作
	$modal.modal('show');
};

/** 打回包裹 **/
var invalidFlag = false;
var invalidPackage = function () {
	if (invalidFlag) {
		return;
	}
	invalidFlag = true;
	var packageId = $("#detailPackageId").val();
	$.ajax({
		type: "POST",
		url: 'package/invalidPackage.json',
		data: {"packageId": packageId},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "操作成功，订单已移入到「待处理」页！"});
				$('#invalidPackageModal').modal('hide');
				$('#packageDetailModal').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
				closeDiv('invalidPackageModal');
			}
			invalidFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			invalidFlag = false;
		}
	});
};

/** 批量打回订单 **/
var batchInvalidFlag = false;
var batchInvalidPackage = function () {
	if (batchInvalidFlag) {
		return;
	}
	batchInvalidFlag = true;
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId'),
		ajaxData = {
			packageIds: packageIds
		},
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		batchInvalidFlag = false;
		return;
	}
	if (shopGroupId) ajaxData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/batchInvalid.json',
		data: ajaxData,
		dataType: "json",
		success: function (data) {
			$("#batchInvalidPackageModal").modal("hide");
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "订单已移入到「待处理」页！");
			refreshAjaxPage();
			$('#loading').modal('hide');
			batchInvalidFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			batchInvalidFlag = false;
		}
	});
};

/** 显示拆分包裹 **/
var showSplitPackage = function (packageId) {
	$("#splitPackageId").val(packageId);
	$("#splitPackageModal").modal("show");
	$.ajax({
		type: "POST",
		url: 'package/getOrderList.htm',
		data: {"packageId": packageId},
		dataType: "html",
		success: function (data) {
			$("#splitPackageTable").html(data);
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 拆分包裹 **/
var splitPackage = function (isMerge) {
	var packageId = $("#splitPackageId").val();
	var orderIds = getCheckBoxValByName("dxmOrderId");
	if (orderIds == '') {
		$.fn.message({type: "error", msg: "请选择要拆分的订单!"});
		return;
	}
	var selectNum = $("input[name='dxmOrderId']:checked").length;
	var allNum = $("input[name='dxmOrderId']").length;
	if (selectNum == allNum) {
		$.fn.message({type: "error", msg: "被拆分的包裹，请至少保留一个订单！"});
		return;
	}
	$.ajax({
		type: "POST",
		url: 'package/splitPackage.json',
		data: {"packageId": packageId, "orderIds": orderIds, "isMerge": isMerge},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "拆分包裹成功!"});
				$('#splitPackageModal').modal('hide');
				$('#packageDetailModal').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
				closeDiv('splitPackageModal');
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 弹窗显示合并包裹 **/
var showMergePackage = function (obj, key) {
	var packageIds = getAllCheckBoxValByName("packageId" + key);
	MYJ.ajax({
		url: 'package/getByPackageIds.htm',
		pointKey: 'getByPackageIds',
		data: {'packageIds': packageIds},
		success: function (data) {
			var $mergePackageTable = $('#mergePackageTable');
			$mergePackageTable.html(data);
			$.each($mergePackageTable.find('tr'), function (tri, trj) {
				var $tr = $(trj),
					$checkInput = $tr.find('input[name="dxmPackageIdName"]'),
					trproductCount = 0,
					trSkuList = '';
				$.each($tr.find('.productSkuInfo'), function (i, j) {
					var $j = $(j),
						skuStr = $j.attr('data-skuStr'),
						productNum = $j.attr('data-productCount');
					trproductCount += +productNum;
					trSkuList += (trSkuList ? '±' : '') + skuStr;
				})
				$checkInput.attr({
					'data-skuStr': trSkuList,
					'data-productCount': trproductCount
				})
			})
			$('#mergePackageModal').modal('show');
		}
	});
};
// 选中列表数据
var changeMergeOrder = function (obj, isChooseAll) {
	// 选择全部
	if (isChooseAll) {
		selAllCurrPage(obj, 'dxmPackageIdName');
	}

	var $checkProductBox = $('#checkProductBox'),
		$checkInput = $('#mergePackageTable').find('input[name="dxmPackageIdName"]:checked'),
		totalSkuNum = 0,
		choseSkuList = [];
	$.each($checkInput, function (i, j) {
		var $j = $(j),
			curOrderSkuList = $j.attr('data-skuStr'),
			curCount = +$j.attr('data-productCount');
		$.each(curOrderSkuList.split('±'), function (skui, skuj) {
			if (choseSkuList.indexOf(skuj) === -1) {
				choseSkuList.push(skuj);
			}
		});
		totalSkuNum += curCount;
	})
	$checkProductBox.addClass('hide');
	if (totalSkuNum > 0) {
		var $totalSkuNum = $checkProductBox.find('.totalSkuNum'),
			$choseSkuNum = $checkProductBox.find('.choseSkuNum');
		$totalSkuNum.text(totalSkuNum);
		$choseSkuNum.text(choseSkuList.length);
		$checkProductBox.removeClass('hide');
	}
}

/** 合并包裹 **/
var mergePackage = function (isShow, obj, key) {

	var packageIds = "";
	if (isShow == 1) {
		/** 可以合并的包裹多余2个，需要弹框选择 **/
		packageIds = getCheckBoxValByName("dxmPackageIdName");
	} else {
		/** 直接合并包裹 **/
		packageIds = getAllCheckBoxValByName("packageId" + key);
	}
	if (packageIds == '' || packageIds == null) {
		$.fn.message({type: "error", msg: "请选择要合并的包裹!"});
		return;
	}
	if (packageIds.indexOf(",") == -1) {
		$.fn.message({type: "error", msg: "请至少选择2个包裹!"});
		return;
	}
	$.ajax({
		type: "POST",
		url: 'package/merge.json',
		data: {"packageIds": packageIds},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "合并成功!"});
				$('#mergePackageModal').modal('hide');
				refreshAjaxPage();

			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 刷新统计数据 **/
var refreshCountNum = function () {
	var $keepState = $('#keepState'),
		storageId = $keepState.data('storageid'),
		isOversea = $keepState.data('isoversea'),
		commitPlatform = $keepState.data('commitplatform');

	$.ajax({
		type: "POST",
		url: 'package/getCountNum.json',
		data: {
            state: $keepState.data('state'),
            storageId: storageId,
            isOversea: isOversea,
            commitPlatform: commitPlatform ? commitPlatform : ''
        },
		dataType: "json",
		success: function (data) {
			$("#allNumSpan").html(data.allNum);
			$("#mergeNumSpan").html(data.mergeNum);
			$("#singleNumSpan").html(data.singleNum);
			$("#splitNumSpan").html(data.splitNum);
			$("#splitedNumSpan").html(data.splitedNum);
			$("#unNeedTrackNum").html(data.unNeedTrackNum);
			$("#applyingNum").html(data.applyingNum);
			$("#applyFailNum").html(data.applyFailNum);
			$("#applySuccessNum").html(data.applySuccessNum);
			$("#unCommitNum").html(data.unCommitNum);
			$("#committingNum").html(data.committingNum);
			$("#commitFailNum").html(data.commitFailNum);
			$("#behindCount").html(data.behindCount);
			$("#failCount").html(data.failCount);
			$("#unCommitCount").html(data.unCommitCount);
			if (data.commitFailNum > 0) {
				$("#commitFailNum").addClass("fW600 fRed");
			} else {
				$("#commitFailNum").removeClass("fW600").removeClass("fRed");
			}
			$("#commitSuccessNum").text(data.commitSuccessNum);
			if(isOversea == 2){
				$('#yucangCommitNum').text(data.ycCommittingNum);
				$('#yuncangCancelNum').text(data.ycCancelNum);
			}
			var authMap = data.authMap;
			if(authMap != null){
				$("#authIdDiv").find("span.wlOrderCount").each(function(){
					var id = $(this).attr("data");
					var val = authMap[id];
					if(val == '' || val == undefined || val == null){
						val = 0;
					}
					$(this).text("（"+val+"）");
				});
			}
			authMap = null;
			$('#approvedCount').data({
				all: data.allNum,
				merge: data.mergeNum,
				single: data.singleNum,
				split: data.splitNum,
				splited: data.splitedNum
			});
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

var refreshApprovedCountNum = function(){
	$("#allNumSpan").html($("#approvedCount").data("all"));
	$("#mergeNumSpan").html($("#approvedCount").data("merge"));
	$("#singleNumSpan").html($("#approvedCount").data("single"));
	$("#splitNumSpan").html($("#approvedCount").data("split"));
	$("#splitedNumSpan").html($("#approvedCount").data("splited"));
};

/** 刷新左侧统计数据 **/
var refreshStateCount = function () {
	$('#paidNum').html('测试数');
	return;
	
	MYJ.ajax({
		url: 'package/getStateCount.json',
		data: {},
		loading: false, //获取订单各个状态的订单数量请求不需要显示loading
		success: function (data) {
			var orderCount = data.orderCount,
				$shippedFailNum = $('#shippedFailNum');

			$('#paidNum').html(orderCount.paidCount);
			$('#approvedNum').html(orderCount.approvedCount);
			$('#processedNum').html(orderCount.processedCount);
			$('#processHomeNum').html(orderCount.processedCount - orderCount.processedOverseaCount - orderCount.processedYuncangCount);
			$('#processOverseaNum').html(orderCount.processedOverseaCount);
			$('#processYuncangNum').html(orderCount.processedYuncangCount);
			$('#allocatedHasNum').html(orderCount.allocatedHasCount);
			$('#allocatedOutNum').html(orderCount.allocatedOutCount);
			$('#allocatedExceptionNum').html(orderCount.allocatedExceptionCount);
			$('#exceptionLi').css('display', orderCount.allocatedExceptionCount > 0 ? '' : 'none');
			$('#shippedingNum').html(orderCount.committingNum);
            $('#behindTrackCountLeft').val(orderCount.behindTrackCount);
			$shippedFailNum.html(orderCount.commitFailNum + orderCount.unCommitNum);
			$('#shippedSuccessNum').html(orderCount.commitSuccessNum);
			$('#refoundNum').html(orderCount.refoundCount);
			$('#voidedNum').html(orderCount.voidedCount);
			$('#committingLi').css('display', orderCount.committingNum > 0 ? '' : 'none');
			if(orderCount.commitFailNum > 0){
				$shippedFailNum.addClass('fRed').addClass('fW600');
			} else {
				$shippedFailNum.removeClass('fRed').removeClass('fW600');
			}
		}
	});
};

/** 打印包裹 **/
var printMb = function (packageId, authId, isScan) {
	// 判断是否选择了菜鸟打印
	if(!checkSelectCainiao(packageId, authId, 0)) {
		checkPrint(packageId, authId, 1, isScan);
		var isCos = $("#isCos").val();
		if(isCos == '' || isCos == undefined){
			isCos = 0;
		}
		var wo = window.open('about:blank', '_blank');
		wo.location.href = "printMb.htm?packageIds=" + packageId + "&authId=" + authId+"&isCos="+isCos;
	}
};

/** 关闭弹层 **/
var closeDiv = function (id) {
	$('#' + id).modal('hide');
	$('#packageDetailModal').modal('hide');
	$('#packageDetailModal').modal('show');
};

/** 编辑物流追踪号 **/
var editTrackNum = function () {

	$("#trackingNumberSpan").hide();
	$("#trackingNum").css("display", "");
	$("#changeProviderSelect").css("display", "");
	$("#providerBtn").html("保存");
	$("#providerSpan").hide();
	$("#providerBtn").attr("onclick", "uploadTrackNum();");
	$("#trackingError").html("");
	$("#trackingError").hide();
	changeProviders();
};
var signMapper = {
    '0': '其他',
    '1': '频繁退货、退款',
    '2': '恶意差评（不合理要求、同行等等）',
    '3': '疑似信用卡诈骗',
    '4': '恶意威胁、敲诈',
    '5': '拍下不付款',
    '6': '偏远地区',
	'7': '货到付款拒收',
	'8': '拒付关税'
};
/**批量标记黑名单,点击先验证是否勾选包裹才能跳出弹层，否则报错拦截**/
var batchBlackList = function () {
	// 如果没有选中所有页，要判断用户是否已选择订单
	var packageIds = getCheckBoxValByName('packageId');

	if (!packageIds) {
		MYJ.message.error('请至少选择一个订单');
		return;
	}
	$('#blacklistBatchModal').modal('show');
};

/**批量标记黑名单**/
var batchSignBlack = function(){
	var ids = getCheckBoxValByName("packageId");
	if (ids === "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	var history = $("#keepState").data("history");
    var $blacklistBatchModal = $('#blacklistBatchModal');
    var signType = $blacklistBatchModal.find('input[type="radio"]:checked').val();
    if (typeof signType === 'undefined') {
        $.fn.message({type: "error", msg: "请选择一项原因"});
        return;
    }
    var reason = $blacklistBatchModal.find('#elseTypeReason').val();
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'blacklist/batchSignBlacklist.json',
		data: {
		    packageIds: ids,
            history : history,
            signType: signType,
            signDetail: signType === '0' ? (reason === '' ? signMapper[signType] : reason) :signMapper[signType]
        },
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code === 0) {
                $blacklistBatchModal.modal('hide');
				batchReturnProcess(data.bor.successList, data.bor.failList, "标记黑名单成功！");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 编辑买家邮箱 **/
var editBuyerEmail = function () {
	var email = $("#buyerEmail").val();
	$("#buyerEmailInput").val(email);
	$("#editBuyerEmailModal").modal("show");
};

/** 保存买家邮箱 **/
var updateBuyerEmail = function () {

	var buyerEmail = $.trim($("#buyerEmailInput").val());
	var validateEmail = /^([a-zA-Z0-9]|[\_|\.|\-])+@([a-zA-Z0-9]|[\_|\.|\-])*\.[a-zA-Z0-9]+$/;
	if(!buyerEmail.match(validateEmail)){
		$.fn.message({type:"error",msg:"邮箱格式不正确"});
		return;
	}
	var packageId = $("#detailPackageId").val();

	$.ajax({
		type: "POST",
		url: 'package/updateBuyerEmail.json',
		data: {"packageId": packageId, "buyerEmail": buyerEmail},
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
				$("#buyerEmail").val(buyerEmail);
				$('#buyerEmailSpan').html(buyerEmail).closest('div').attr('title', buyerEmail);
				$.fn.message({type: "success", msg: "保存买家邮箱成功！"});
				closeEditBuyerEmail();

			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 关闭编辑买家邮箱页面 **/
var closeEditBuyerEmail = function () {
	$("#editBuyerEmailModal").modal("hide");
	$("#packageDetailModal").modal('hide');
	$("#packageDetailModal").modal('show');
};

// 编辑买家IOSS税号
var editBuyerIOSS = function () {
	var $editBuyerIOSSModal = $('#editBuyerIOSSModal'),
		taxNumber = $('#buyerIOSSVal').val();
	$editBuyerIOSSModal.find('#buyerIOSSInput').val(taxNumber);
	$editBuyerIOSSModal.modal('show');
}
// 保存IOSS税号
var updateBuyerIOSS = function () {
	var $buyerIOSSInput = $('#buyerIOSSInput'),
		buyerIOSS = $.trim($buyerIOSSInput.val()),
		dxmOrderId = $.trim($('#detailPackageId').val()),
		orderNumber = $.trim($('#orderNumberVal').val()),	// 订单号
		packageNumber = $.trim($('#dxmPackageNumDetailSpan').attr('data-id'));
	if (!buyerIOSS) {
		MYJ.message.error('请填写税号(IOSS)');
		$buyerIOSSInput.focus();
		return;
	} else if (buyerIOSS.length > 100) {
		MYJ.message.error('税号(IOSS)的字符长度不能超过100');
		$buyerIOSSInput.focus();
		return;
	}
	MYJ.ajax({
		url: 'order/updateDxmOrderVat.json',
		data: {
			dxmOrderId: dxmOrderId,
			orderId: orderNumber,
			packageNumber: packageNumber,
			ukVAT: buyerIOSS
		},
		success: function (res) {
			if (!+res.code) {
				$('#buyerIOSSVal').val(buyerIOSS);
				$('#buyerTaxNumberSpan').html(buyerIOSS).attr('title', buyerIOSS);
				MYJ.message.success('保存税号(IOSS)成功！');
				closeEditBuyerIOSS();
			} else {
				MYJ.message.error(res.msg? res.msg : '网络错误，请稍后重试！');
			}
		}
	});
}
// 关闭编辑买家IOSS税号页面
var closeEditBuyerIOSS = function () {
	var $editBuyerIOSSModal = $('#editBuyerIOSSModal'),
		taxNumber = $('#buyerIOSSVal').val();
	$editBuyerIOSSModal.find('#buyerIOSSInput').val(taxNumber);
	$editBuyerIOSSModal.modal('hide');
}

/** 展示物流追踪号 **/
var showTrackNum = function (providerName) {
	$("#trackingNumberSpan").css("display", "");
	$("#trackingNum").hide();
	$("#providerSpan").css("display", "");
	$("#providerSpan").html(providerName);
	$("#changeProviderSelect").hide();
	$("#providerBtn").html("更改");
	$("#providerBtn").attr("onclick", "editTrackNum();");
	$("#reApplayTrackBtn").addClass('hide');
};

var initSetSmtInfo = function () {
	var agentNameType = $("#agentNameType").val();
	if (agentNameType == 22) {
		// 表示速卖通
		$("#expressTrackNum").val($("#expressNumberHidden").val());
		expressAjax();
		//serviceKeyAjax();
	}
};

/** 设置速卖通信息 **/
var setSmtInfo = function () {
	expressAjax();
	var expressId = $("#expressId").val();
	if (expressId == -1) {
		var expressName = $("#expressNameHidden").val();
		str = '<div class="form-group has-error has-feedback" style="margin:0;"><input type="text" value="" id="expressInput" placeholder="请输入" class="form-control" style="border-color:#ccc"/><span class="glyphicon glyphicon-remove form-control-feedback inputClose" style="right:0;color:#999;pointer-events:auto;"></span></div>';
		$("#expressTd").html(str);
		$("#expressInput").val(expressName);
	}

	var agentNameType = $("#agentNameType").val();
	if (agentNameType == 22) {
		// 表示速卖通
		$("#smtExpressDiv").css("display", "");
	} else {
		// 隐藏速卖通物流承运商设置
		$("#smtExpressDiv").css("display", "none");
	}

	var agentType = $("#agentType").val();

	if (agentType == 2 || agentType == -1) {
		// 系统对接
		$("#trackNumLabel").html("自动获取");
	} else {
		var allotType = $("#allotType").val();
		if (allotType == 1) {
			$("#trackNumLabel").html("号码池分配");
		} else if (allotType == 0) {
			$("#trackNumLabel").html("手动上传");
		} else {
			$("#trackNumLabel").html("无");
		}
	}

	$('#expressTrackNum').val($('#expressNumberHidden').val());
	var isBattery = $('#isBatteryHidden').val(),
        isAneroidMarkup  = $('#isLiquidHidden').val();//含非液体化妆品

    $('#isBattery').prop('checked', +isBattery !== 0);
    $('#isLiquid').prop('checked', +isAneroidMarkup === 1);
};

/** 输入物流追踪号 **/
var uploadTrackNum = function () {
	var packageId = $('#detailPackageId').val();
	var trackNum = $.trim($('#uploadTrackNumInput').val());
	if (!trackNum) {
		$.fn.message({type: "error", msg: "请输入物流追踪号!"});
		return;
	}
	var authId = $('#detailPackageAuthId').val();
	if (!+authId) {
		$.fn.message({type: "error", msg: "请选择物流方式!"});
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: 'POST',
		url: 'package/uploadTrackNum.json',
		data: {packageId: packageId, authId: authId, trackNum: trackNum},
		dataType: 'json',
		success: function (data) {
			var code = data.code;
			if (!+code) {
				$.fn.message({type: "success", msg: "物流追踪号保存成功!"});
				$('#detailPackageTrackNum').val(trackNum);
				$('#detailPackageAuthId').val(authId);
				$('#trackNumberDiv').html(trackNum).addClass('col-sm-3 pTop6');

				// 在未编辑页面申请单号按钮和上传按钮隐藏
				$('#uploadTrackNumBtn').closest('div').addClass('myj-hide');
				/*$("#uploadTrackNumInput").hide();*/

			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			$('#loading').modal('hide');
			$('#packageDetailModal').modal('hide').modal('show');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	return false; //return false,防止触发form表单的提交,不要去掉这行代码
};

/** 设置amazonFBA海外仓物流 **/
var setAmazonFBAProvider = function(dis, provider){
	$("#amazonFBAPlatformDiv1").css("display", dis);
	$("#amazonFBAPlatformDiv2").css("display", dis);
	$("#amazonFBAPlatformProvider1").html(provider);
	$("#amazonFBAPlatformProvider2").html(provider);
	$("#amazonFBAProviderDiv1").css("display", dis);
	$("#amazonFBAProviderDiv2").css("display", dis);
};

/** 重新申请运单号 **/
var reApplyFlag = false,
    behindTrackNumberType = null, //判断是物流商单号还是跟踪单号,true=是物流商单号，false不是
    updateShipInfoAuthSelectVal = '',
    forwardOrderNumberId = '';
var reApplyTrackNum = function (packageId, n) {
	if(reApplyFlag){
		return;
	}
	reApplyFlag = true;
	var expressId = $('#expressSelect').val();											// 国内快递ID
	if (!expressId) {
		expressId = -1;
	}
	var expressName = $('#expressSelect option:selected').text();						// 国内快递名称
	if (expressId == -1) {
		expressName = $('#expressInput').val();
	}
	var expressTrackNum = $('#expressTrackNum').val(),									// 快递单号
		isBattery = 0,
		isCheck = $('#isBattery').is(':checked');									    // 是否含电

	var isBatteryHtml = '否';
	if (isCheck) {
		isBattery = 1;
		isBatteryHtml = '是';
	}
	var isLiquid = 0,
		isLiquidCheck = $('#isLiquid').is(':checked'),									// 是否液体
		isLiquidHtml = '否';
	if (isLiquidCheck) {
		isLiquid = 1;
		isLiquidHtml = '是';
	}
	var $updateShipInfoAuthSelect = $('#updateShipInfoAuthSelect'),
        $updateShipInfoAuthSelectOpt = $updateShipInfoAuthSelect.find('option:selected'),
		authId = $updateShipInfoAuthSelect.val();									// 物流方式ID
	if (n == 1) {
		isBattery = $('#isBatteryHidden').val();
		isLiquid = $('#isLiquidHidden').val();
		isBatteryHtml = isBattery == 1 ? '是' : '否';
		isLiquidHtml = isLiquid == 1 ? '是' : '否';
		authId = $('#detailPackageAuthId').val();
		expressName = $.trim($('#expressNameHtml').text()); //如果是在非编辑状态外点击的获取跟踪号，则应该拿table表格里面的国内快递名称
	}
	if (!+authId) {
		$.fn.message({type: "error", msg: "请选择物流方式!"});
		reApplyFlag = false;
		return;
	}
	var agentType = $updateShipInfoAuthSelectOpt.attr('agentype'),
		allotType = $updateShipInfoAuthSelectOpt.attr('allotType'),
		agentApAuthName = $updateShipInfoAuthSelectOpt.text(),		// 物流方式名称
		agentNameType = $updateShipInfoAuthSelectOpt.attr('agentNameType'),
		sizeType = $updateShipInfoAuthSelectOpt.attr('sizeType'),
		agentPackageCountType = $updateShipInfoAuthSelectOpt.attr('agentPackageCountType'),
		length = $('#postLength').val(),												// postPony相关开始
		width = $('#postWidth').val(),
		height = $('#postHeight').val(),
		weight = $('#postWeight').val(),
		lengthUnit = $('#lengthUnit').val(),
		weightUnit = $('#weightUnit').val(),											// postPony相关结束
		agentPackageCount = $('#agentPackageCount').val(),											// postPony相关结束
		isHomeCheck = $('#isHomeAddr').is(':checked'),									// 是否家庭地址
		isHomeAddrHtml = '否',
		isHomeAddr = 0;
	var showCodAmount = $updateShipInfoAuthSelectOpt.attr('isBack');		// 出口易是否显示COD金额
	if (isHomeCheck) {
		isHomeAddr = 1;
		isHomeAddrHtml = '是';
	}
	if (agentNameType == 22) {
		// 如果是速卖通线上发货
		var apacPickUpType = $updateShipInfoAuthSelectOpt.attr('apacPickUpType');		// 揽收类型   0:上门揽收 1：1 快递运输到仓库 （需要选物流） 2  卖家自送
		var providerType = $updateShipInfoAuthSelectOpt.attr('providerType');			// 物流方式类型  1:中俄航空  2：4PX
		if(n == 0){
			var fCode = $('#detailPackageFcode').val();
			// if ((apacPickUpType == 1 || providerType == 1) && expressId == 0 && fCode == '') {
			// 	$.fn.message({type: "error", msg: "请选择国内快递!"});
			// 	reApplyFlag = false;
			// 	return;
			// }
			// if ((apacPickUpType == 1 || providerType == 1) && (expressTrackNum == null || expressTrackNum == '' && fCode == '')) {
			// 	$.fn.message({type: "error", msg: "请输入快递单号！"});
			// 	reApplyFlag = false;
			// 	return;
			// }
			if (apacPickUpType == 0 && providerType != 1) {
				expressName = '上门揽收';
				expressId = -1;
				expressTrackNum = '无需填写';
			}else if (apacPickUpType == 2 && providerType != 1) {
				expressName = '卖家自送到仓库';
				expressId = -1;
				expressTrackNum = '无需填写';
			}
			if (providerType == 2) {
				expressTrackNum = '无需填写';
			}
		} else {
			if (apacPickUpType == 0 && providerType != 1) {
				expressName = '上门揽收';
				expressTrackNum = '无需填写';
			}else if(apacPickUpType == 2 && providerType != 1){
				expressName = '卖家自送到仓库';
				expressTrackNum = '无需填写';
			}
			if (providerType == 2) {
				expressTrackNum = '无需填写';
			}
		}
	} else if ((agentNameType == 105 && n == 0) || (agentNameType == 655 && n == 0) || (agentNameType == 448 && n == 0) || (agentNameType == 734 && n == 0) || (sizeType == 1 && n == 0)) {
		// postPony物流
		var a = validateNum(length, 'postLength', '长度');
		if (a) {
			reApplyFlag = false;
			return;
		}
		var b = validateNum(width, 'postWidth', '宽度');
		if (b) {
			reApplyFlag = false;
			return;
		}
		var c = validateNum(height, 'postHeight', '高度');
		if (c) {
			reApplyFlag = false;
			return;
		}
		if(agentNameType != 655 && agentNameType != 448 && agentNameType != 734 && sizeType != 1){
			var d = validateNum(weight, 'postWeight', '重量');
			if (d) {
				reApplyFlag = false;
				return;
			}
		} else if (agentPackageCountType == 1) {
			var c = validateNum(agentPackageCount, 'agentPackageCount', '包裹数量');
			if (c) {
				return;
			}
		}
		if(agentNameType == 655){
			expressId = $('#inlandExpressCode').val();
			expressName = $('#inlandExpressCode option:selected').text();
			expressTrackNum = $('#inlandExpressNumber').val();
		}

	} else if ((agentNameType == 256 || agentNameType == 419) && n == 0) {
		// 中乌速递乌克兰专线
		expressId = $('#zwsdExpressSelected').val();
		expressName = $('#zwsdExpressSelected option:selected').text();
		expressTrackNum = $('#zwsdExpressTrackNumber').val();
		if(expressId == 0 && (expressName === '请选择' || expressName === '')){
			reApplyFlag = false;
			$.fn.message({type:"error", msg:"请选择国内快递!"});
			return;
		}
		if(!expressTrackNum){
			reApplyFlag = false;
			$.fn.message({type:"error", msg:"请输入快递单号！"});
			return;
		}
	}
	if (n == 0) {
		n = 1;
	} else if (n == 1) {
		n = 2;
	}
	$('#reApplayTrackBtn').prop('disabled', true);
	$('#reApplyTrackNumBtn').prop('disabled', true);
	var codAmount = $('#heLianExpressCodAmount').val();
	var agentPackageCount = $('#agentPackageCount').val();
	$.ajax({
		type: 'POST',
		url: 'order/reApply.json',
		data: {
			packageId: packageId,
			authId: authId,
			n: n,
			expressId: expressId,
			expressName: expressName,
			expressTrack: expressTrackNum,
			isBattery: isBattery,
			isLiquid: isLiquid,
			length: length,
			width: width,
			height: height,
			lengthUnit: lengthUnit,
			weight: weight,
			weightUnit: weightUnit,
			isHomeAddr: isHomeAddr,
			codAmount: codAmount,
			agentPackageCount: agentPackageCount
		},
		dataType: 'json',
		success: function (data) {
			var code = data.code;
			if (!+code) {
				var trackNum = data.trackNum,
                    forwardOrderId = data.forwardOrderId,
					behindState = data.behindState,
                    $trackNumberDiv = $('#trackNumberDiv'),
				    codType = $updateShipInfoAuthSelectOpt.attr('codType'),
					sizeType = $updateShipInfoAuthSelectOpt.attr('sizeType');

                behindTrackNumberType = behindState; //获取状态，true是物流商单号，false是跟踪单号
                if(behindState){
                    $('#trackingNumber,#reApplayTrackBtn').addClass('hide');
                    $('#trackingNumberBox').removeClass('hide').css('display','');
                    updateShipInfoAuthSelectVal = $updateShipInfoAuthSelect.val(); //获取当前物流方
                    forwardOrderNumberId = forwardOrderId; //获取物流商单号
                    $trackNumberDiv.closest('div.form-group').find('label').empty().html('物流商单号：');
                    // 后置单号的订单隐藏编辑按钮(订单状态不等于待审核，待处理，运单号申请)
                    var state = $("#keepState").data("state");
                    if (state != 'paid' && state != 'approved' && state != 'processed') {
                        $('#shipInfoBtn').hide();
                    }
                }else{
                    $('#trackingNumber,#reApplayTrackBtn').removeClass('hide');
                    $('#trackingNumberBox').addClass('hide');
                    forwardOrderNumberId = '';
                    $trackNumberDiv.closest('div.form-group').find('label').empty().html('跟踪单号：');
                }
				if (!trackNum && !behindState) {
                    var msg = strFilterUrl(data.msg);
					$.fn.message({type: "error", msg: "申请失败!失败原因：" + msg});

				} else {
					$.fn.message({type: "success", msg: "保存物流信息成功!"});
					$('#shippingProviderSpan').removeClass('glyphicon-remove fRed').addClass('glyphicon-ok fGreen');
					$('#shippingProviderTr').html(strEscapeCharacter(agentApAuthName));
					$('#agentProviderDiv').html(strEscapeCharacter(agentApAuthName));
					$('#detailPackageAuthId').val(authId);
					$('#expressId').val(expressId);
					$('#expressNameHidden').val(expressName);
					$('#detailPackageTrackNum').val(trackNum);
                    $trackNumberDiv.html(trackNum || forwardOrderId).addClass('col-sm-3 pTop6');
					$('#expressNumberHidden').val(expressTrackNum);
					$('#isBatteryHidden').val(isBattery);
					$('#isLiquidHidden').val(isLiquid);
					$('#agentType').val(agentType);
					$('#agentNameType').val(agentNameType);
					$('#allotType').val(allotType);
					$('#detailPackageFcode').val(data.forwardOrderId);
					$('#expressNameHtml').html(expressName);
					$('#expressNumberHtml').html(expressTrackNum);
					$('#isBatteryHtml').html(isBatteryHtml);
					$('#isLiquidHtml').html(isLiquidHtml);
					var weightUnitHtml = '盎司';
					if (weightUnit === 'g') {
						weightUnitHtml = '克';
					}
					$('#lengthHtml').html(length);												// postPony相关开始
					$('#widthHtml').html(width);
					$('#heightHtml').html(height);
					$('#lengthUnitHtml').html(lengthUnit);
					$('#weightHtml').html(weight);
					$('#weightUnitHtml').html(weightUnitHtml);
					$('#isAddrHomeHtml').html(isHomeAddrHtml);									// postPony相关结束
					$('#agentPackageCountHtml').html(agentPackageCount);									// postPony相关结束

					$('#zwsdExpressNameHtml').html(expressName);
					$('#zwsdExpressNumberHtml').html(expressTrackNum);

					if (agentNameType == 22) {
						// 显示速卖通物流承运商设置
						$('#smtAgentDiv').css('display', '');
						$('#postPonyDiv').css('display', 'none');
						$('#zwsdAgentDiv').css('display','none');
                        $('#heLianDiv').css('display', 'none');
					} else if (agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1) {
						// postPony
						$('#smtAgentDiv').css('display', 'none');
						$('#zwsdAgentDiv').css('display','none');
                        $('#heLianDiv').css('display', 'none');
						$('#postPonyDiv').css('display', '');
					}  else if (agentNameType == 256 || agentNameType == 419) {
						// 中乌速递乌克兰专线
						$('#smtAgentDiv').css('display','none');
						$('#postPonyDiv').css('display','none');
                        $('#heLianDiv').css('display', 'none');
						$('#zwsdAgentDiv').css('display','');
					} else if (agentNameType == 353 || (agentNameType == 704 && apacPickUpType == 1) || (agentNameType == 3 && showCodAmount == 1 ) || (codType == 1 && showCodAmount == 1)) {
                        $('#smtAgentDiv').css('display', 'none');
                        $('#postPonyDiv').css('display', 'none');
                        $('#zwsdAgentDiv').css('display','none');
                        $('#heLianDiv').css('display', '');
					} else if (agentNameType == 170){
						$('#smtAgentDiv').css('display', 'none');
						$('#postPonyDiv').css('display', 'none');
						$('#zwsdAgentDiv').css('display','none');
						$('#heLianDiv').css('display', 'none');
						$('#shipInfoBtn').addClass('hide');
					} else {
						// 隐藏速卖通物流承运商设置
						$('#smtAgentDiv').css('display', 'none');
						$('#postPonyDiv').css('display', 'none');
						$('#zwsdAgentDiv').css('display','none');
                        $('#heLianDiv').css('display', 'none');
					}

					if (agentPackageCountType == 1) {
						$("[name='agentPackageCountDisplay']").css("display", "");
					} else {
						$("[name='agentPackageCountDisplay']").css("display", "none");
					}

					// 在未编辑页面申请单号按钮和上传按钮隐藏
                    $('#uploadTrackNumBtn').closest('div').addClass('myj-hide');

					// 更改打印面单事件
					$('#detailPrintMbBtn').attr('onclick', "printMb('" + packageId + "','" + authId + "');");
					cancelShipInfo();
					// 刷新统计数字
					refreshStateCount();
				}
			} else {
				var msgs = data.msg;
				if(msgs) { //把报错信息中的style和script干掉，避免xss注入
					msgs = msgs.replace(/style/g, '').replace(/script/g, '');
				}
				$.fn.message({type: "error", msg: strFilterUrl(msgs)});
				$('#trackNumberDiv').find('.errorMsgShow, .errorMsgHide').html(strFilterUrl(msgs));
			}
			$('#reApplayTrackBtn').prop('disabled', false);
			$('#reApplyTrackNumBtn').prop('disabled', false);
			reApplyFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			$('#reApplayTrackBtn').prop('disabled', false);
			reApplyFlag = false;
		}
	});
};

/** 修改amazonFba的物流方式 **/
var updateAmazonFbaProvider = function(obj){
	var provider = $(obj).val();
	if(provider == ''){
		$.fn.message({type: "error", msg: "请选择对应平台物流！"});
		return;
	}
	var packageId = $("#detailPackageId").val();
	$.ajax({
		type: "POST",
		url: 'amazonFBAOrderProvider/addFBAProvider.json',
		data: {"packageId":packageId, "provider":provider},
		dataType: "json",
		success: function (data) {
			if(data.code != 0){
				$.fn.message({type: "error", msg: data.msg});
			} else {
				$("#amazonFABSelect1").val(provider);
				$("#amazonFABSelect2").val(provider);
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 批量操作处理结果 **/
var batchReturnProcess = function (successList, failList, successMsg,importShippingUpFormData) {
	$('#loading').modal('hide');
	var successNum = successList.length;		// 成功数量
	var failNum = failList.length;			// 失败数量

	if (successNum > 0 && failNum == 0) {
		// 全部成功，只显示提示框信息
		var msg = "操作成功" + successNum + "条";
		if (successMsg != "") {
			msg += "," + successMsg;
		}
		$.fn.message({type: "success", msg: msg});

	} else {
		// 一部分成功，一部分失败
		var failDetail = "<table class='errorMsgTab'><tr><td><span>失败原因：</span></td><td>";
		if (failList.length > 0) {
			for (var i = 0; i < failList.length; i++) {
				var obj = failList[i];
				if (obj.id == null || obj.id == "") {
					failDetail = failDetail + "<p style='margin-bottom:10px;'>" + obj.msg + "</p>";
				} else {
					if (importShippingUpFormData && 1 === importShippingUpFormData.isOrder){
						failDetail = failDetail + "<p style='margin-bottom:10px;'>「订单号：" + obj.id + "」" + obj.msg + "</p>";
					}else {
						failDetail = failDetail + "<p style='margin-bottom:10px;'>「包裹号：" + obj.id + "」" + obj.msg + "</p>";
					}
				}
			}
		}
		failDetail += '</td></tr></table>';
		$("#operateSuccessNum").html(successNum);
		$("#operateSuccessDetail").html(successMsg);
		$("#operateFailNum").html(failNum);
		failDetail = strFilterUrl(failDetail);
		$("#operateFailDetail").html(failDetail);
		if (successNum > 0) {
			$("#successDl").css("display", "");
		} else {
			$("#successDl").css("display", "none");
		}
		$("#batchOperateRetModal").modal("show");
	}
};

/** 批量重新申请运单号 **/
var batchReApplyFlag = false;
var batchReApplyTrackNum = function (type) {
	if (batchReApplyFlag) {
		return;
	}
	batchReApplyFlag = true;
    var packageIds = '';
    if(type == 1){
        packageIds = getCheckBoxValByName("packageId");
        if(packageIds == ""){
            $.fn.message({type:"error",msg:"请至少选择一个包裹"});
			batchReApplyFlag = false;
            return;
        }
	}
	$("#syncFromAutoReApplyModal").modal("show");
	var p = 0;		// 记录进度条的值
	$("#autoReApplyProgressBar").css("width", "0");
	$("#syncFromAutoReApplyModal_status").html("获取中...");
	$("#syncFromAutoReApplyModal_processDetail").html("");
	$.ajax({
		type: "POST",
		url: 'order/batchReApply.json',
        data: {
            "type": type,
            "packageIds": packageIds
        },
		dataType: "json",
		success: function (data) {

			var uuid = data.uuid;
			checkProcessStatus(uuid, function(data){
				var num 	= data.num % 100;
				var status = "获取中...";

				if(num < p && data.code != 1){
					// 为了去掉变为n->0时的动画效果，在此先隐藏，然后再置0，最后再定时显示出来
					$("#autoReApplyProgressBar").css("display", "none");
					setTimeout(function(){
						$("#autoReApplyProgressBar").css("display", "");
					},1000);
				}
				p = num;
				if(data.code==0){
					$("#autoReApplyProgressBar").css("width", num + "%");
				}else{
					status = "已完成!";
					$("#autoReApplyProgressBar").css("width", "100%");
					$("#autoReApplyProgressBar").removeClass("active");
				}
				$("#syncFromAutoReApplyModal_status").html(status);
				$("#syncFromAutoReApplyModal_processDetail").html(data.msg);
			});
			batchReApplyFlag = false;
		},
		error: function () {
			$('#loading').modal('hide');
			batchReApplyFlag = false;
		}
	});
};

/** 批量一键合并 **/
var batchMerge = function () {
	var mergeIds = getCheckBoxValByName("mergePackageId");
	if (mergeIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个合并订单"});
		return;
	}
	$('#batchMergeConfigModal').modal('show');
	$('#batchMergeConform').attr('onclick', 'batchMergeConform("'+mergeIds+'")')

};

// 批量合并确认
var batchMergeConform = function(mergeIds) {
	var isOnlyMergeProvider = $("input[name='selectProviderType']:checked").val();
	if (isOnlyMergeProvider == "") {
		isOnlyMergeProvider = 0;
	}
	$('#batchMergeConfigModal').modal('hide');
	$('#loading').modal('show');
	$.ajax({
		type: 'POST',
		url: 'package/batchMerge.json',
		data: {
			'mergeId': mergeIds,
			'isOnlyMergeProvider' : isOnlyMergeProvider
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			var successList = data.bor.successList;
			var failList = data.bor.failList;
			batchReturnProcess(successList, failList, "");
			refreshAjaxPage();
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};
/** 更改物流方式（已发货状态） **/
var changeProvider = function () {
	$("#trackingNumberSpan").hide();
	$("#providerSpan").hide();
	$("#trackingNum").css("display", "");
	$("#changeProviderSelect").css("display", "");
	$("#trackNumBtn").attr("onclick", "uploadTrackNum();");
	$("#trackNumBtn").html("保存");
};

/** 国内快递ajax ***/
var expressAjax = function () {
	var expressId = $("#expressId").val();
	var platform = $("#detailPlatform").val();
	$.ajax({
		type: "POST",
		url: 'smtExpress/getExpress.json',
		data: {"platform" : platform},
		dataType: "json",
		success: function (data) {
			var list = data.list,
				str = "<option value='0'>请选择</option>",
				shippingId = $('#updateShipInfoAuthSelect').val(), // 当前选中的物流方式值
				smtOrderExpressId = getSmtDetailOrderSaveExpress(shippingId);

			for (var i = 0; i < list.length; i++) {

				if (platform === 'smt' && smtOrderExpressId) {
					// 速卖通线上发货，如果上次保存到某物流的揽收方式，则默认选中
					if (+smtOrderExpressId === (+list[i].companyId)) {
						str += "<option value='" + list[i].companyId + "' selected>" + list[i].name + "</option>";
					} else {
						str += "<option value='" + list[i].companyId + "'>" + list[i].name + "</option>";
					}
				} else {
					if (+expressId === (+list[i].companyId)) {
						str += "<option value='" + list[i].companyId + "' selected>" + list[i].name + "</option>";
					} else {
						str += "<option value='" + list[i].companyId + "'>" + list[i].name + "</option>";
					}
				}
			}
			var $expressSelect = $('#expressSelect');

			$expressSelect.html(str).chosen('destroy').chosen({
				search_contains: true//注册插件
			});
			$('#expressSelect_chosen').css('width','278px');

			// 中乌速递乌克兰专线回显
			$("#zwsdExpressSelected").html(str);
			var inlandExpressId = $("#inlandExpressId").val();
			$("#zwsdExpressSelected option").each(function () {
				if($(this).val() == inlandExpressId){
					$(this).prop("selected",true);
				}
			});
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 速卖通线上发货（批量） **/
var smtOnlineExpressAjax = function (obj) {
	$.ajax({
		type: "POST",
		url: 'smtExpress/getExpress.json',
		data: {},
		dataType: "json",
		success: function (data) {
			$(obj).html("");
			var list = data.list;
			for (var i = 0; i < list.length; i++) {
				str += "<option value='" + list[i].companyId + "'>" + list[i].name + "</option>";
			}
			$(obj).html(str);
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 编辑包裹地址信息 **/
var editPackageAddr = function (val) {
	if (val == 1) {
		$("#dpAddrTable span").hide();
		$("#dpAddrTable input").show();
		$("#detailCountry").show();
		$("#dpAddrCancelBtn").show();
		$("#dpAddrBtn").html("保存");
		$("#dpAddrBtn").attr("onclick", "updateDpAddress();");

	} else {
		$("#dpAddrTable span").show();
		$("#dpAddrTable input").hide();
		$("#detailCountry").hide();
		$("#dpAddrCancelBtn").hide();
		$("#dpAddrBtn").html("修改");
		$("#dpAddrBtn").attr("onclick", "editPackageAddr(1);");
	}
};

/** 取消编辑地址 **/
var cancelEditAddr = function () {
	$("#zip").val($("#zipSpan").html());
	$("#city").val($("#citySpan").html());
	$("#mobile").val($("#mobileSpan").html());
	$("#contact").val($("#contactSpan").html());
	$("#address2").val($("#address2Span").html());
	$("#province").val($("#provinceSpan").html());
	$("#phoneNumber").val($("#phoneNumberSpan").html());
	$("#detailAddress").val($("#detailAddressSpan").html());
	editPackageAddr();
};

/** 引用新地址 **/
var useNewAddr = function () {
	$("#contact").val($("#contactSpan").text());					// 联系人
	$("#detailAddress").val($("#detailAddressSpan").text());		// 详细地址
	$("#address2").val($("#address2Span").text());					// 地址2
	$("#city").val($("#citySpan").text());							// 城市
	$("#province").val($("#provinceSpan").text());					// 州,省份
	$("#country").val($("#countrySpan").val());						// 国家
	$("#zip").val($("#zipSpan").text());							// 邮编
	$("#phoneNumber").val($("#phoneNumberSpan").text());			// 电话
	$("#mobile").val($("#mobileSpan").text());						// 手机
};

/*** 执行修改收货人地址 ***/
var updateDpAddress = function () {
	var packageId = $("#detailPackageId").val();			// 包裹ID
	var zip = $.trim($('#zip').val());				// 邮编
	var phone = $.trim($('#phoneNumber').val());		// 电话
	var country = $("#country").val();					// 国家
	var countryStr = $("#country option:selected").text();	// 国家显示值
	var province = $("#province").val();					// 州,省份
	var city = $("#city").val();						// 城市
	var contact = $("#contact").val();					// 联系人
	var mobile = $("#mobile").val();					// 手机
	var detailAddr = $("#detailAddress").val();			// 详细地址
	var address2 = $("#address2").val();					// 地址2

	$.ajax({
		type: "POST",
		url: 'dxmPackageAddr/update.json',
		data: {
			"packageId": packageId,
			"zip": zip,
			"phone": phone,
			"country": country,
			"province": province,
			"city": city,
			"contact": contact,
			"mobile": mobile,
			"detailAddr": detailAddr,
			"address2": address2
		},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "保存收货地址成功!"});
				$("#zipSpan").text(zip);						// 邮编
				$("#phoneNumberSpan").text(phone);				// 电话
				$("#countrySpan").text(countryStr);				// 国家
				$("#provinceSpan").text(province);				// 州,省份
				$("#citySpan").text(city);						// 城市
				$("#contactSpan").text(contact);				// 联系人
				$("#mobileSpan").text(mobile);					// 手机
				$("#detailAddrSpan").text(detailAddr);			// 详细地址
				$("#address2Span").text(address2);				// 地址2
				$("#country").val(country);
				editPackageAddr();

			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 显示重新生成包裹号弹层 **/
var showGeneratePackNum = function () {
	$("#changePackageNumModel").modal("show");
};

/** 执行更换包裹号 **/
var changePackageNum = function () {
	$("#changePackageNumModel").modal("hide");

	var packageId = $("#detailPackageId").val();															// 包裹ID
	var apAuthId = $("#updateShipInfoAuthSelect").val();												// 物流方式ID
	var agentType = $("#updateShipInfoAuthSelect option:selected").attr("agentype");
	var allotType = $("#updateShipInfoAuthSelect option:selected").attr("allotType");
	var agentNameType = $("#updateShipInfoAuthSelect option:selected").attr("agentNameType");
	var agentApAuthName = $("#updateShipInfoAuthSelect option:selected").text();						// 物流方式名称
	var apacPickUpType = $("#updateShipInfoAuthSelect option:selected").attr("apacPickUpType");			// 揽收类型   0:上门揽收 1：快递运输到仓库 （需要选物流）  2  卖家自送到仓库
	var providerType = $("#updateShipInfoAuthSelect option:selected").attr("providerType");			// 物流方式类型  1:中俄航空  2：4PX
	var sizeType = $("#updateShipInfoAuthSelect option:selected").attr("sizeType");			// 物流方式类型  1:中俄航空  2：4PX
	var agentPackageCountType = $("#updateShipInfoAuthSelect option:selected").attr("agentPackageCountType");			// 包裹数量

	var expressId = $("#expressSelect").val();											// 国内快递ID
	var expressName = $("#expressSelect option:selected").text();						// 国内快递名称
	if (expressId == undefined && (apacPickUpType == 1 || providerType == 1)) {
		expressName = $("#expressInput").val();
		expressId = -1;
	}
	var expressTrackNum = $("#expressTrackNum").val();									// 快递单号

	var length = $("#postLength").val();												// postPony相关开始
	var width = $("#postWidth").val();
	var height = $("#postHeight").val();
	var weight = $("#postWeight").val();
	var lengthUnit = $("#lengthUnit").val();
	var weightUnit = $("#weightUnit").val();											// postPony相关结束
	var agentPackageCount = $("#agentPackageCount").val();											// postPony相关结束

	if (agentNameType == 22) {
		// 速卖通线上发货
		if ((apacPickUpType == 1 || providerType == 1) && expressId == 0 && (expressName === '请选择' || expressName === '')) {
			$.fn.message({type: "error", msg: "请选择国内快递!"});
			return;
		}

		//先不验证必填了，可在分拨组包时填写
		// if ((apacPickUpType == 1 || providerType == 1) && (expressTrackNum == null || expressTrackNum == '')) {
		// 	$.fn.message({type: "error", msg: "请输入快递单号！"});
		// 	return;
		// }
		if (apacPickUpType == 0 && providerType != 1) {
			expressName = "上门揽收";
			expressId = -1;
			expressTrackNum = "无需填写";
		}else  if (apacPickUpType == 2 && providerType != 1) {
			expressName = "卖家自送到仓库";
			expressId = -1;
			expressTrackNum = "无需填写";
		}
		if ((apacPickUpType == 0||apacPickUpType == 2) && providerType == 2) {
			expressTrackNum = "无需填写";
		}
	} else if (agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1) {
		// postPony物流
		var a = validateNum(length, "postLength", "长度");
		if (a) {
			return;
		}
		var b = validateNum(width, "postWidth", "宽度");
		if (b) {
			return;
		}
		var c = validateNum(height, "postHeight", "高度");
		if (c) {
			return;
		}
		if(agentNameType != 655 && agentNameType != 448 && agentNameType != 734 && sizeType != 1){
			var d = validateNum(weight, "postWeight", "重量");
			if (d) {
				return;
			}
		} else if (agentPackageCountType == 1) {
			var c = validateNum(agentPackageCount, 'agentPackageCount', '包裹数量');
			if (c) {
				return;
			}
		}
	}
	var isChecked = $("#isBattery").is(':checked');										// 是否含电
	var isBattery = 0;
	var isBatteryHtml = "否";
	if (isChecked) {
		isBattery = 1;
		isBatteryHtml = "是";
	}
	var isLiquidChecked = $("#isLiquid").is(':checked');								// 是否液体
	var isLiquid = 0;
	var isLiquidHtml = "否";
	if (isLiquidChecked) {
		isLiquid = 1;
		isLiquidHtml = "是";
	}
	var isHomeCheck = $("#isHomeAddr").is(':checked');									// 是否家庭地址
	var isHomeAddrHtml = "否";
	var isHomeAddr = 0;
	if (isHomeCheck) {
		isHomeAddr = 1;
		isHomeAddrHtml = "是";
	}
	if (apAuthId == 0 || apAuthId == '' || apAuthId == null) {
		$.fn.message({type: "error", msg: "请选择物流方式!"});
		return;
	}
	$("#reApplayTrackBtn").prop('disabled', true);
	$("#reApplyTrackNumBtn").prop('disabled', true);
	$('#loading').modal('show');

	var cfCode = $("#changePackageFcode").val();
	$.ajax({
		type: "POST",
		url: 'package/changePackageNum.json',
		data: {
			"packageId": packageId,
			"authId": apAuthId,
			"expressId": expressId,
			"expressName": expressName,
			"expressTrack": expressTrackNum,
			"isBattery": isBattery,
			"isLiquid": isLiquid,
			"length": length,
			"width": width,
			"height": height,
			"lengthUnit": lengthUnit,
			"weight": weight,
			"weightUnit": weightUnit,
			"isHomeAddr": isHomeAddr,
			"fCode": cfCode
		},
		dataType: "json",
		success: function (data) {

			if (data.code == 0) {
				$("#packageNumTd").text(data.packageNum);
				$("#newPackageNumTd").text(data.newPackageNum);
				$("#trackNumTd").text(data.trackNum);
				$("#newTrackNumTd").text(data.newTrackNum);
				$("#changePackageNumSuccessModel").modal("show");
				$("#dxmPackageNumDetailSpan").text(data.newPackageNum);

				$("#shippingProviderSpan").removeClass("glyphicon-remove fRed").addClass("glyphicon-ok fGreen");
				$("#shippingProviderTr").html(strEscapeCharacter(agentApAuthName));
				$("#agentProviderDiv").html(strEscapeCharacter(agentApAuthName));
				$("#detailPackageAuthId").val(apAuthId);
				$("#expressId").val(expressId);
				$("#expressNameHidden").val(expressName);
				$("#detailPackageTrackNum").val(data.newTrackNum);
				$("#trackNumberDiv").html(data.newTrackNum);
				$("#expressNumberHidden").val(expressTrackNum);
				$("#isBatteryHidden").val(isBattery);
				$("#isLiquidHidden").val(isLiquid);
				$("#agentType").val(agentType);
				$("#agentNameType").val(agentNameType);
				$("#allotType").val(allotType);
				$("#expressNameHtml").html(expressName);
				$("#expressNumberHtml").html(expressTrackNum);
				$("#isBatteryHtml").html(isBatteryHtml);
				$("#isLiquidHtml").html(isLiquidHtml);

				var weightUnitHtml = "盎司";													// postPony相关开始
				if (weightUnit == 'g') {
					weightUnitHtml = "克";
				}
				$("#lengthHtml").html(length);
				$("#widthHtml").html(width);
				$("#heightHtml").html(height);
				$("#lengthUnitHtml").html(lengthUnit);
				$("#weightHtml").html(weight);
				$("#weightUnitHtml").html(weightUnitHtml);
				$("#isAddrHomeHtml").html(isHomeAddrHtml);									// postPony相关结束
				$("#agentPackageCountHtml").html(agentPackageCount);									// postPony相关结束
				if (agentNameType == 22) {
					// 显示速卖通物流承运商设置
					$("#smtAgentDiv").css("display", "");
					$("#postPonyDiv").css("display", "none");
				} else if (agentNameType == 105 || agentNameType == 655 || agentNameType == 448 || agentNameType == 734 || sizeType == 1) {
					// postPony
					$("#smtAgentDiv").css("display", "none");
					$("#postPonyDiv").css("display", "");
				} else {
					// 隐藏速卖通物流承运商设置
					$("#smtAgentDiv").css("display", "none");
					$("#postPonyDiv").css("display", "none");
				}

				if (agentPackageCountType == 1) {
					$("[name='agentPackageCountDisplay']").css("display", "");
				} else {
					$("[name='agentPackageCountDisplay']").css("display", "none");
				}

				// 在未编辑页面申请单号按钮和上传按钮隐藏
				$("#uploadTrackNumBtn").hide();
				$("#uploadTrackNumInput").hide();
				$("#trackNumberDiv").addClass("col-sm-3 pTop6");

				$("#changePackageFcode").val("");
				// 更改打印面单事件
				$("#detailPrintMbBtn").attr("onclick", "printMb('" + packageId + "','" + apAuthId + "');");
				cancelShipInfo();

			} else {
				var msg = data.msg;

				$('#changePackageFcode').val(data.fCode);
				$('#changePackageNumErr')[msg.indexOf('%#W7Ox0Ze%#') !== -1 ? 'html' : 'text'](strFilterUrl(msg));
				$('#changePackageNumErrModel').modal('show');
			}
			$('#loading').modal('hide');
			$('#reApplayTrackBtn').prop('disabled', false);
			$('#reApplyTrackNumBtn').prop('disabled', false);
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

var closeChangePackageNum = function () {
	$("#changePackageNumErrModel").modal("hide");
	$("#changePackageNumSuccessModel").modal("hide");
	$("#packageDetailModal").modal("hide");
	$("#packageDetailModal").modal("show");
};

var closeChangePackageNumDialog = function () {
	$("#changePackageNumModel").modal("hide");
	$("#changePackageNumSuccessModel").modal("hide");
	$("#packageDetailModal").modal("hide");
	$("#packageDetailModal").modal("show");
};

/************************** 重新生成包裹号 **************************/

/** 显示重新生成包裹号弹层 **/
var showNewPackageNum = function (packageId,type) {
	var agentNameType = $("#agentNameType").val()
	$("#updateTrackNumPackageId").val(packageId);
	if(type == 1){
		$("#updateTrackNumModel").modal("show");
	}else if(type == undefined || type == ''){
		//判断订单是否在
		$.ajax({
			type: "POST",
			url: 'order/hasChangedAgent.json',
			data: {
				"packageId": packageId,
				"agentNameType": agentNameType
			},
			dataType: "json",
			async:false,
			success: function (data) {
				if(data.code == 0){
					$("#updateTrackNumModel").modal("show");
				}else if(data.code == -1){
					$.fn.message({type: "error", msg: data.errMsg});
				}
			},
			error: function () {
				$('#loading').modal('hide');
				$("#updateTrackNumModel").modal("show");
			}
		});
	}
};

/** 生成物流方式弹层 **/
var showUpdateTrackNum = function () {
	var packageId = $("#updateTrackNumPackageId").val();
	$("#executeChangePackageNumModel").html("");
	$.ajax({
		type: "POST",
		url: 'package/showPackaegDetail.htm',
		data: {"packageId": packageId},
		dataType: "html",
		success: function (data) {
			$("#updateTrackNumModel").modal("hide");
			$("#executeChangePackageNumModel").html(data);
			$("#executeChangePackageNumModel").modal("hide");
			$("#executeChangePackageNumModel").modal("show");
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
	$("#dxmPackageDetailDiv").empty();
};

/** 重新申请运单号（已发货和虚拟发货） **/
var reApplyShipFlag = false;
var isWait = 0;
var reApplyShipTrackNum = function (packageId) {
	isWait = 0;//先初始化
	if(reApplyShipFlag) return;
	reApplyShipFlag = true;
	var expressId = $("#expressSelect").val();											// 国内快递ID
	if (expressId == undefined || expressId == '') {
		expressId = -1;
	}
	var expressName = $("#expressSelect option:selected").text();						// 国内快递名称
	if (expressId == -1) {
		expressName = $("#expressInput").val();
	}
	var expressTrackNum = $("#expressTrackNum").val();									// 快递单号
	var isBattery = 0;
	var b = $("#isBattery").is(':checked');									// 是否含电
	if (b) {
		isBattery = 1;
	}
	var authId = $("#updateShipInfoAuthSelect").val();									// 物流方式ID
	var agentType = $("#updateShipInfoAuthSelect option:selected").attr("agentype");
	var allotType = $("#updateShipInfoAuthSelect option:selected").attr("allotType");
	var sizeType = $("#updateShipInfoAuthSelect option:selected").attr("sizetype");
	var agentPackageCountType = $("#updateShipInfoAuthSelect option:selected").attr("agentPackageCountType");
	var agentApAuthName = $("#updateShipInfoAuthSelect option:selected").text();		// 物流方式名称

	var agentNameType = $("#updateShipInfoAuthSelect option:selected").attr("agentNameType");
	var length = null;
	var width = null;
	var height = null;
	var lengthUnit = null;
	var weight = null;
	var weightUnit = null;
	var agentPackageCount = null;
	if (agentNameType == 22) {
		// 如果是速卖通线上发货
		var $updateShipInfoAuthSelect = $('#updateShipInfoAuthSelect').find('option:selected'),
			apacPickUpType = $updateShipInfoAuthSelect.attr('apacPickUpType'),			// 揽收类型   0:上门揽收 1： 快递运输到仓库 （需要选物流） 2   卖家自送到仓库
			providerType = $updateShipInfoAuthSelect.attr('providerType');			// 物流方式类型  1:中俄航空  2：4PX
		if((apacPickUpType == 1 || providerType == 1) && expressId == 0 && expressName === '请选择' && expressTrackNum){
			$.fn.message({type: 'error', msg: '请选择国内快递!'});
			reApplyShipFlag = false;
			return;
		}

		// if ((apacPickUpType == 1 || providerType == 1) && (expressTrackNum == null || expressTrackNum == '')) {
		// 	$.fn.message({type: "error", msg: "请输入快递单号！"});
		// 	reApplyShipFlag = false;
		// 	return;
		// }
		if (apacPickUpType == 0 && providerType != 1) {
			expressName = "上门揽收";
			expressId = -1;
			expressTrackNum = "无需填写";
		}else  if (apacPickUpType == 2 && providerType != 1) {
			expressName = "卖家自送到仓库";
			expressId = -1;
			expressTrackNum = "无需填写";
		}
		if (providerType == 2) {
			expressTrackNum = "无需填写";
		}
	}else if(agentNameType == 256 || agentNameType == 419){
		// 中乌速递乌克兰专线
		expressId = $("#zwsdExpressSelected").val();
		expressName = $("#zwsdExpressSelected option:selected").text();
		expressTrackNum = $("#zwsdExpressTrackNumber").val();
		if(expressId == 0 && (expressName === '请选择' || expressName === '')){
			$.fn.message({type:"error", msg:"请选择国内快递!"});
			reApplyShipFlag = false;
			return;
		}
		if(expressTrackNum == ""){
			$.fn.message({type:"error", msg:"请输入快递单号！"});
			reApplyShipFlag = false;
			return;
		}
	}else if(agentNameType == 655){
		expressId = $('#inlandExpressCode').val();
		expressName = $('#inlandExpressCode option:selected').text();
		expressTrackNum = $('#inlandExpressNumber').val();
		length = $('#postLength').val();												// 尺寸
		width = $('#postWidth').val();
		height = $('#postHeight').val();
		lengthUnit = $('#lengthUnit').val();
	}else if(agentNameType == 448 || agentNameType == 734 || sizeType == 1){
		length = $('#postLength').val();												// 尺寸
		width = $('#postWidth').val();
		height = $('#postHeight').val();
		lengthUnit = $('#lengthUnit').val();
		weight = $('#postWeight').val();
		weightUnit = $('#weightUnit').val();
	}else if(agentNameType == 105){
		length = $('#postLength').val();												// 尺寸
		width = $('#postWidth').val();
		height = $('#postHeight').val();
		lengthUnit = $('#lengthUnit').val();
		weight = $('#postWeight').val();
		weightUnit = $('#weightUnit').val();
	}

	if (agentPackageCountType == 1) {
		agentPackageCount = $('#agentPackageCount').val();
	}

	var codAmount = $('#heLianExpressCodAmount').val();

	var $forwardOrderId = $('#forwardOrderId'),
		fCode = $forwardOrderId.val();

	isWait = 1;//在开始发请求获取的时候也提示下，不让优化立即关闭
	$('#reApplayTrackBtn').prop('disabled', true);
	$.ajax({
		type: 'POST',
		url: gitWinLocHref() + 'order/reApply.json',
		data: {
			packageId: packageId,
			authId: authId,
			n: 0,
			expressId: expressId,
			expressName: expressName,
			expressTrack: expressTrackNum,
			isBattery: isBattery,
			fCode: fCode,
            codAmount: codAmount,
			length: length,
			width: width,
			height: height,
			lengthUnit: lengthUnit,
			weight:weight,
			weightUnit:weightUnit,
			agentPackageCount: agentPackageCount
		},
		dataType: 'json',
		success: function (data) {
			var code = data.code,
				trackNum = data.trackNum,				// 物流追踪号
				agentTrackNum = data.agentTrackNum,		// agentTrackNum
				applyCloseTime = data.applyCloseTime,
				destWarehouseCode = data.destWarehouseCode,
				destWarehouseName = data.destWarehouseName,
				$trackingNumber = $('#trackingNumber');

			fCode = data.forwardOrderId;			// fCode
			if (!+code) {
				if (!trackNum) {
                    var msg = strFilterUrl(data.msg);
					$.fn.message({type: 'error', msg: '申请失败!失败原因：' + msg});
					isWait = msg.indexOf('非立即返回单号') !== -1 ? 1 : 0//如果是非立即返回单号的，还需要等待，则在关闭的时候要弹层提示
				} else {
					isWait = trackNum ? 0 : 1;//如果成功但没有立即返回运单号，也要在关闭时弹层提示
					$.fn.message({type: 'success', msg: '申请运单号成功!'});
					$trackingNumber.val(trackNum).prop('disabled', true);
					removeDisabled($trackingNumber);
				}
			} else {
				$.fn.message({type: 'error', msg: strFilterUrl(data.msg)});
				isWait = strFilterUrl(data.msg).indexOf('非立即返回单号') !== -1 ? 1 : 0//如果是非立即返回单号的，还需要等待，则在关闭的时候要弹层提示
			}
			$forwardOrderId.val(fCode);
			$('#agentTrackNum').val(agentTrackNum);
			if (+agentNameType === 22 || +agentNameType === 256) {
				var channelCode = data.channelCode,
					lpNumber = data.lpNumber;
				$('#channelCode').val(channelCode);
				$('#lpNumber').val(lpNumber);
				$('#applyCloseTime').val(applyCloseTime);
				$('#destWarehouseCode').val(destWarehouseCode);
				$('#destWarehouseName').val(destWarehouseName);
				if (fCode && fCode !== 'null') {
					$('#updateShipInfoAuthSelect').prop('disabled', true);
					$trackingNumber.prop('disabled', true).parent().find('.fRed').remove();
					$('#reApplayTrackBtn').after('<span class="fRed">申请失败,请重新获取</span>');
				}
			}
			if (+agentNameType === 28) {
				var hubWarehouseCode = data.hubWarehouseCode;
				$('#destWarehouseCode').val(destWarehouseCode);
				$('#destWarehouseName').val(destWarehouseName);
				$('#hubWarehouseCode').val(hubWarehouseCode);
			}
			if (trackNum && trackNum !== 'null') {
				$trackingNumber.parent().find('.fRed').remove();
			}
			$('#reApplayTrackBtn').prop('disabled', false);
			reApplyShipFlag = false;

			if(fCode || trackNum && trackNum !== 'null'){
				$('#updateTrackNumLabel1').find('[name="agentRadio"]').prop('disabled', true);
				$('#updateShipInfoAuthSelect').prop('disabled', true).trigger('chosen:updated');
				if(trackNum && trackNum !== 'null') $trackingNumber.prop('disabled', true);
			}
		},
		error: function () {
			$('#loading').modal('hide');
			$('#reApplayTrackBtn').prop('disabled', false);
			reApplyShipFlag = false;
			isWait = 0;
		}
	});
};

/** 执行更改运单号（虚拟发货和发货） **/
var updateTrackNum = function (packageId, isCommit) {
	var trackNum = $.trim($('#trackingNumber').val());
	if (!trackNum) {
		$.fn.message({type: 'error', msg: '请输入跟踪单号！'});
		return;
	}
	var isHandle = 1;
	var disabled = $('#trackingNumber').prop('disabled');
	if("disabled" == disabled){
		isHandle = 0;
	}
	if(isCommit == 1){
		// wish拆分订单提交至平台
		isCommit = $("input[name='isCommitPlatform']:checked").val();
		if(isCommit == undefined || isCommit == ''){
			$.fn.message({type: "error", msg: "请选择平台替换运单号选项值"});
			return;
		}
	}
	if(isCommit == undefined){
		isCommit = 1;
	}
	var isBattery = 0;
	var b = $("#isBattery").is(':checked');									// 是否含电
	if (b) {
		isBattery = 1;
	}
	var isLiquid = 0;
	var c = $("#isLiquid").is(':checked');									// 是否含电
	if (c) {
		isLiquid = 1;
	}
	var fCode = $("#forwardOrderId").val();
	if (fCode == undefined) {
		fCode = "";
	}
	var agentTrackNum = $("#agentTrackNum").val();
	if (agentTrackNum == undefined) {
		agentTrackNum = "";
	}
	var wishCountry = $("#wishCountry").val();
	if(wishCountry == undefined){
		wishCountry = "";
	}
	var lpNumber = $("#lpNumber").val();
	if (lpNumber == undefined) {
		lpNumber = "";
	}
	var channelCode = $("#channelCode").val();
	if (channelCode == undefined) {
		channelCode = "";
	}
	var applyCloseTime = $("#applyCloseTime").val();
	if (applyCloseTime == undefined) {
		applyCloseTime = "";
	}
	var destWarehouseCode = $("#destWarehouseCode").val();
	if (destWarehouseCode == undefined) {
		destWarehouseCode = "";
	}
	var destWarehouseName = $("#destWarehouseName").val();
	if (destWarehouseName == undefined) {
		destWarehouseName = "";
	}
	var hubWarehouseCode = $("#hubWarehouseCode").val();
	if (hubWarehouseCode == undefined) {
		hubWarehouseCode = "";
	}

	var $updateShipInfoAuthSelect = $('#updateShipInfoAuthSelect'),
		authId = $updateShipInfoAuthSelect.val(),
		agentRadio = $('input[name="agentRadio"]:checked').val();						// 获取单号方式

	if(agentRadio == 0){
		isBattery = 0;
		isLiquid = 0;
		isHandle = 1;
		fCode  = '';
		agentTrackNum = '';
		lpNumber = '';
		channelCode = '';
		applyCloseTime = '';
		destWarehouseCode = '';
		destWarehouseName = '';
		hubWarehouseCode = '';
		var authIdStr = $('#updateShipInfoAuthSelect1 option:selected').val();
		if (authIdStr == '') {
			$.fn.message({type: "error", msg: "请选择物流方式！"});
			return;
		}
		authId = $('#updateShipInfoAuthSelect1 option:selected').text();
	}
	if (authId == '' || authId == 0) {
		$.fn.message({type: "error", msg: "请选择物流方式！"});
		return;
	}

	var $expressTrackNum = $('#expressTrackNum'),
		expressTrackNum = $.trim($expressTrackNum.val()),									// 快递单号
		$option = $updateShipInfoAuthSelect.find('option:selected'),   //物流方式
		agentNameType = $option.attr('agentNameType'),
		apacPickUpType = $option.attr('apacPickUpType');     // 揽收类型 0  上门揽收  1   快递运输到仓库    2  卖家自送到仓库

	if(+agentRadio === 1 && +agentNameType === 22 && +apacPickUpType === 1 && expressTrackNum && expressTrackNum.toLowerCase() === 'none') {
		if(!$('.trackNumErrorMsg').length) {
			var $selectNode = $updateShipInfoAuthSelect.is(':visible') ? $updateShipInfoAuthSelect : $updateShipInfoAuthSelect.next('div'),
				$selectBox = $selectNode.closest('td').length ? $selectNode.closest('td') : $selectNode.closest('div');//兼容节点

			$selectNode.addClass('border-red');
			$selectBox.append('<div class="f-red trackNumErrorMsg">快递单号不能输入none</div>');
		}
		return;
	}

	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/updateTrackNum.json',
		data: {
			"packageId": packageId,
			"authId": authId,
			"trackNum": trackNum,
			"fCode": fCode,
			"agentTrackNum":agentTrackNum,
			"isBattery": isBattery,
			"isLiquid":isLiquid,
			"isCommit": isCommit,
			"wishCountry" : wishCountry,
			"lpNumber": lpNumber,
			"channelCode": channelCode,
			"applyCloseTime": applyCloseTime,
			"destWarehouseCode": destWarehouseCode,
			"destWarehouseName": destWarehouseName,
			"hubWarehouseCode": hubWarehouseCode,
			"isHandle" : isHandle
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "更改运单号成功!"});
				$("#executeChangePackageNumModel").modal("hide");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
				$("#executeChangePackageNumModel").modal("hide");
				$("#executeChangePackageNumModel").modal("show");
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/*******************************批次start*********************************/
// 检测是否在作业中
var isProcessing = function(state){
	$.ajax({
		type: "POST",
		url: 'dxmBatch/isProcessing.json',
		data: {},
		dataType: "json",
		success: function (data) {
			if(data.code == 0){
				// 作业中
				window.location.href = 'dxmBatch/packing.htm?id='+data.batchId;
			} else {
				var url = "dxmBatch/index.htm?batchState="+state;
				batchStateLoadUrl(url);
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

var batchStateLoadUrl = function(url){
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: url,
		data: {},
		dataType: "html",
		success: function (data) {
			$('#rightBody').html(data);
			$("#rightBody").css("display", "");
			$('#loading').modal('hide');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

// 选择订单的某个状态
var selBatchState = function (id, state) {
	$("#liOne").find(".treeBackgrounda").removeClass("treeBackgrounda");
	$("#"+id).parent().addClass("treeBackgrounda");

	if(state == '1' || state == '2'){
		// 待包装和包装中需要检测
		isProcessing(state);
	} else {
		var url = "";
		if(state == '-2'){
			url = "batchDetail/freeIndex.htm";
		} else if(state == '0' || state == '3'){
			url = "dxmBatch/index.htm?batchState="+state;
		} else {
			url = "dxmBatch/createBatchIndex.htm";
		}
		batchStateLoadUrl(url);
	}
};

/*******************************批次end*********************************/

/************************** 重新生成包裹号 **************************/
/** 显示备注弹出框 **/
var showComment = function () {
	$('#commentContent').val('');
	$('#commentType').val('sys_picking');
	changeCommentColor($('#commentType'));
	$('#beizu').modal('show');
	orderTemplateMethod($('#commentContent'), 'sys_picking');
};

/** 设置备注选中颜色 **/
var setCommentColor = function (obj) {
	$(obj).parent().find(".bgCommentFocus").removeClass("bgCommentFocus");
	$(obj).addClass("bgCommentFocus");
};

/** 设置拣货说明颜色 **/
var setJhCommentColor = function (obj) {
	var color = $(obj).attr("class"),
		colorVal = $(obj).attr("value");
	$(obj).closest(".dropdown").find("[pid='colorSpan']").attr("class", color);
	$(obj).closest(".dropdown").find('.jhCommentInput').val(colorVal);
};

/** 增加备注 **/
var isAddCmt = false;
var addComment = function () {
    if (isAddCmt) {
        return;
    }
    isAddCmt = true;
	var packageId = $('#detailPackageId').val(),
		commentType = $('#commentType').val(),
		commentInfo = $('#commentType option:selected').text(),
		content = $.trim($('#commentContent').val()),
		color = $('#commentColorDiv').find('.bgCommentFocus').attr('data-val'),
		history = $("#keepState").data("history");
	if(!history) {
		history = "";
	}
	if (!content && commentType === 'sys_service') {
        $.fn.message({type: 'error', msg: '备注内容不能为空!'});
        isAddCmt = false;
        return;
    }
	if (content.length > 500) {
		$.fn.message({type: 'error', msg: '备注内容长度不能超过500个字符!'});
        isAddCmt = false;
		return;
	}
	$.ajax({
		type: 'POST',
		url: 'dxmPackageComment/add.json',
		data: {
            packageId: packageId,
            commentType: commentType,
            content: content,
            color: color,
			history:history
		},
		dataType: 'json',
		success: function (data) {
            isAddCmt = false;
            var code = data.code;
			if (!+code) {
				var $tr = $('<tr></tr>'),
					$obj = $('#jhCommentTrDetail'),
                    $commentTr = $('#commentTr');

                $.fn.message({type: 'success', msg: '备注信息增加成功!'});

				if (commentType === 'sys_service') {
					if (!$obj.length) {
                        $tr.html('<td class="f-left contentTd"></td><td>' + data.createTime + '</td>' +
							'<td>' + commentInfo + '</td><td>' + data.operator + '</td>' +
							'<td><a href="javascript:" onclick="deletePackageComment(' + data.id + ',this);">删除</a></td>');
                        $commentTr.after($tr);
                        $tr.find('.contentTd').text(content);
					} else {
                        $tr.html('<td class="f-left contentTd"></td><td>' + data.createTime + '</td>' +
                            '<td>' + commentInfo + '</td><td>' + data.operator + '</td>' +
                            '<td><a href="javascript:" onclick="deletePackageComment(' + data.id + ',this);">删除</a></td>');
                        $obj.after($tr);
                        $tr.find('.contentTd').text(content);
                    }
					if (!content) $obj.remove();
				} else {
                    $obj.remove();
                    $tr.html('<td class="f-left contentTd"></td><td>' + data.createTime + '</td>' +
                        '<td>' + commentInfo + '</td><td>' + data.operator + '</td>' +
                        '<td><a href="javascript:" onclick="editPackageComment();">编辑</a>' +
						'&nbsp;<a href="javascript:" onclick="deletePackageComment(' + data.id + ',this);">删除</a></td>');
                    $tr.attr({'id': 'jhCommentTrDetail', 'style': 'color:#' + color + ';'});
                    $commentTr.after($tr);
                    $tr.find('.contentTd').text(content);
					if (!content) $obj.remove();
				}
			} else {
				$.fn.message({type: 'error', msg: data.msg});
			}
			closeDiv('beizu');
        },
		error: function () {
			$('#loading').modal('hide');
            isAddCmt = false;
        }
	});
};

/** 编辑备注 **/
var editPackageComment = function () {
	$('#commentContent').val('');
	$('#commentType').val('sys_picking');
	changeCommentColor($('#commentType'));
	$('#beizu').modal('show');
	orderTemplateMethod($('#commentContent'), 'sys_picking');
};

/** 批量显示备注信息 **/
var showBatchComment = function (commentType) {
	var packageIds = getCheckBoxValByName('packageId'),
		$loading = $('#loading'),
		history = $('#keepState').data('history');

	if (!packageIds) {
		$.fn.message({type: 'error', msg: '请至少选择一个订单'});
		return;
	}
	commentType = commentType ? commentType : 0;//0：拣货说明  1：客服备注
	$loading.modal('show');
	$.ajax({
		type: 'POST',
		url: gitWinLocHref() + 'dxmPackageComment/getByPackIds.htm',
		data: {packageIds: packageIds, commentType: commentType, history: history === 'all' ? 'history' : ''},
		dataType: 'html',
		success: function (data) {
			$loading.modal('hide');
			$('#loading').modal('hide');
			$('#batchCommentInfo').html(data).modal('hide').modal('show').attr('data-type', commentType);//标记下是拣货说明还是客服备注：1客服备注 0：拣货说明
		},
		error: function () {
			$loading.modal('hide');
		}
	});
};

/**批量修改收件人地址信息*/
var showBatchAddr = function () {
	var packageIds = getCheckBoxValByName("packageId");
	if (packageIds == "") {
		$.fn.message({type: "error", msg: "请至少选择一个订单"});
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/getAddrsByPackIds.json',
		data: {
			"packageIds": packageIds
		},
		dataType: "json",
		success: function (data) {
			var addrStr = getAddrStr(data.orderList, data.countryList, packageIds),
				$batchPackAddrTable = $('#batchPackAddrTable');
			$batchPackAddrTable.html(addrStr);

			/*搜索插件调用 start*/
			$batchPackAddrTable.find('.chosen-select-fixed').chosen('destroy').chosen({
				search_contains: true//注册插件
			});
			$batchPackAddrTable.find('.chosen-search').find('input').attr('placeholder','支持中文、英文、二字码搜索');
			$batchPackAddrTable.find('.chosen-container').css('marginTop','4').css('width','170px');
			$batchPackAddrTable.find('.chosen-drop').css('width','300');
			/*end*/
			$('#loading').modal('hide');
			$('#batchPackageAddr').modal('hide').modal('show');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});

	//如果有速卖通平台，则加载速卖通隐私相关js
	var $isOrderPlatformBySmt = $('#isOrderPlatformBySmt');
	if ($isOrderPlatformBySmt.length) {
		//SMT隐私
		var smtAeSecTokenJsArr = [
			'https://g.alicdn.com/ali-data-safe/securesdk_v3/0.0.4/sec-min.js',
			'https://g.alicdn.com/sd/eco-opensecenv/2.0.3/js/axios_min.js',
			'https://g.alicdn.com/code/npm/@ali/ae-securesdk/0.0.3/aeSecToken.js',
			gitWinLocHref() + 'static/js/order/smtDecrypt.js?v=' + $isOrderPlatformBySmt.attr('data-jsVersion')
		];
		$.each(smtAeSecTokenJsArr, function (i, j) {
			asyncLoadingJSFile({
				src: j,
				async: false
			});
		});
	}
};

/**
 * 批量编辑订单收件人信息（改）
 * @BATCHEDITADR 抽象公共
 * @handleValue 数据的value值处理 obj：数据对象，key：要取值的key
 * @cacheCountryData 存储请求回来的国家数据 arr：国家数据，数组类型
 * @getConutryStr 生成国家选择 isSmt: 是不是速卖通的包裹， selected： 回显值
 * @getItemStr 生成表格单行  data: 包裹数据，addr：地址数据，isTextNode：是否只显示文本（smt加密时为true），saveData：是否存储包裹数据
 * @getPackageData 取包裹的信息 id: 包裹id
 *
 **/
var BATCHEDITADR = (function($, win, doc, o){
	var countryList = null;
	var batchEditAdrInfo = {};
	var optionStr = '<option value="&{value}" &{selected}>&{name}</option>';
	var inputHtml = '<input class="form-control borderRdio &{className}" type="text" name="&{name}" role="&{name}" maxlength="&{maxLength}" value="&{value}"/>';
	var textareaHtml = '<textarea class="form-control" rows="2" name="&{name}" role="&{name}" maxlength="&{maxLength}" style="resize: none;">&{value}</textarea>';
	var eyeHtml = '<a class="mRight10 batchModalShowSmtAdrInfo" href="javascript:" data-type="0" title="点击查看地址信息" data-info="&{id},&{orderId},&{oaid}"><i class="iconfont icon_eye"></i></a>';
	var eyeHtmlDecrypt = '<a class="mRight10 batchModalShowSmtAdrInfoDecrypt" href="javascript:" data-type="0" title="点击查看地址信息" data-info="&{id},&{orderId},&{oaid}"><i class="iconfont icon_eye"></i></a>';
	var editBtn = '<a class="smtAdrEdit" data-id="&{id}" href="javascript:">编辑</a>';
	var hiddenIpt = '<input type="hidden" class="form-control" name="orderIds" value="&{id}"/>';
	o.handleValue = function(obj, key){
		var value = '';
		if(obj && obj[key]){
			value = obj[key];
		}
		return value;
	};
	o.cacheCountryData = function(arr){
		countryList = arr;
	};
	o.getConutryStr = function(isSmt, selected){
		var str = '<select class="form-control chosen-select-fixed" name="countries">';
		str += optionStr.format({name: '请选择', value: '', selected: ''});
		$.each(countryList, function(i, j){
			var code = isSmt ? j.smtCode : j.code;
			var name = j.countryCh + '（' + j.countryEn+' - ' + j.code + '）';
			str += optionStr.format({name: name, value: code, selected: selected === code ? 'selected' : ''});
		});
		str += '</select>';
		return str;
	};
	o.getItemStr = function(data, addr, isTextNode, saveData){
		var _t = this;
		if(saveData) batchEditAdrInfo[data.id] = data;
		return htmlTemplateChange('batchEditAdrListItemHtml', {
			orderIdNode: isTextNode ? '' : hiddenIpt.format({id: data.id}),
			className: isTextNode ? '' : 'v-top m-top5',
			editBtn: isTextNode ? editBtn.format({id: data.id}) : '',
			eyeAction: isTextNode ? eyeHtml.format({id: data.id, orderId: data.orderId, oaid: data.oaid}): '',
			eyeActionDecrypt: !isTextNode && data.oaid && data.platform === 'smt' ? eyeHtmlDecrypt.format({id: data.id, orderId: data.orderId, oaid: data.oaid}): '',
			packageNumber: data.packageNumber,
			nameNode: isTextNode ? _t.handleValue(addr, 'contactPerson') : inputHtml.format({name: 'contactPersons', value: _t.handleValue(addr, 'contactPerson'), maxLength: 150, className: ''}),
			phoneNode: isTextNode ? _t.handleValue(addr, 'phoneNumber') : inputHtml.format({name: 'phoneNumbers', value: _t.handleValue(addr, 'phoneNumber'), maxLength: 100, className: ''}),
			mobileNode: isTextNode ? _t.handleValue(addr, 'mobile') : inputHtml.format({name: 'mobiles', value: _t.handleValue(addr, 'mobile'), maxLength: 20, className: ''}),
			emailNode: isTextNode ? _t.handleValue(addr, 'email') : inputHtml.format({name: 'emails', value: _t.handleValue(addr, 'email'), maxLength: 100, className: 'batchPackInfoEmails'}),
			companyNode: isTextNode ? _t.handleValue(addr, 'companyName') : inputHtml.format({name: 'companyName', value: _t.handleValue(addr, 'companyName'), maxLength: 20, className: ''}),
			taxNumberNode: isTextNode ? _t.handleValue(addr, 'taxNumber') : inputHtml.format({name: 'taxNumber', value: _t.handleValue(addr, 'taxNumber'), maxLength: 20, className: ''}),
			provincesNode: isTextNode ? _t.handleValue(addr, 'province') : inputHtml.format({name: 'provinces', value: _t.handleValue(addr, 'province'), maxLength: 200, className: ''}),
			cityNode: isTextNode ? _t.handleValue(addr, 'city') : inputHtml.format({name: 'cities', value: _t.handleValue(addr, 'city'), maxLength: 100, className: ''}),
			zipNode: isTextNode ? _t.handleValue(addr, 'zip') : inputHtml.format({name: 'zips', value: _t.handleValue(addr, 'zip'), maxLength: 30, className: ''}),
			detailAddressNode: isTextNode ? _t.handleValue(addr, 'detailAddress') : textareaHtml.format({name: 'detailAddresses', value: _t.handleValue(addr, 'detailAddress'), maxLength: 300, className: ''}),
			address2Node: isTextNode ? _t.handleValue(addr, 'address2') : textareaHtml.format({name: 'address2s', value: _t.handleValue(addr, 'address2'), maxLength: 200, className: ''}),
			apartmentNumberNode: isTextNode ? _t.handleValue(addr, 'apartmentNumber') : inputHtml.format({name: 'apartmentNumber', value: _t.handleValue(addr, 'apartmentNumber'), maxLength: 200, className: ''}),
			countryStr: isTextNode ? _t.handleValue(addr, 'country') : this.getConutryStr(data.platform === 'smt',  _t.handleValue(addr, 'country'))
		});
	};
	o.getPackageData = function(id){
		return 	batchEditAdrInfo[id];
	};
	return o;
})(jQuery, window, document, {});

/** 获取地址拼接字符串 **/
var getAddrStr = function(orderList, countryList, packageIds){
	BATCHEDITADR.cacheCountryData(countryList);
	var trStr = '<tr>'+
		'<th class="f-left p-left10">包裹号</th>'+
		'<th class="f-left p-left10"><div>'+
		'<div> 姓名/电话/手机/邮箱 <a class="m-left5" href="javascript:" onclick="batchUpdateModal(2);">（修改）</a></div>'+
		'</div></th>'+
		'<th class="f-left p-left10">'+
		'<div>公司/税号</div>'+
		'</th>'+
		'<th class="f-left p-left10"><div>'+
		'<div>国家/州省/城市/邮编 <a class="m-left5" href="javascript:" onclick="batchUpdateModal(1);">（修改）</a></div>'+
		'</div>'+
		'</th>'+
		'<th class="f-left p-left10">地址</th>'+
		'<th class="f-center p-left10 min80">操作<input type="hidden" name="packageIds" value="'+packageIds+'"/><input type="hidden" id="batchAddrOrderState" name="orderState" value=""/></th>'+
		'</tr>';
	$.each(orderList, function(i, j){
		trStr += BATCHEDITADR.getItemStr(j, j.dxmPackageAddr, j.platform === 'smt' && typeof j.oaid !== 'undefined', true);
	});
	return trStr;
};

/** 更换类型 **/
var changeCommentColor = function (obj, val) {
	var commentType = $(obj).val();		// 备注类型
	var packageId = $("#detailPackageId").val();
	if (val == 1) {
		packageId = $("#commentPackageId").val();
	}
	if (commentType == 'sys_picking') {
		if (val == 1) {
			$("#commentColorFormGroup1").css("display", "");
		} else {
			$("#commentColorFormGroup").css("display", "");
		}
		$.ajax({
			type: "POST",
			url: 'dxmPackageComment/getByPackId.json',
			data: {"packageId": packageId},
			dataType: "json",
			success: function (data) {
				var comment = data.dxmPackageComment;
				var content = "";
				var color = "009926";
				if (comment != null) {
					content = comment.content;
					color = comment.commentColor;
				}
				var packComment = "";
				if (val == 1) {
					$("#commentContent1").val(content);
					packComment = $("#commentColorDiv1").find("a[data-val='" + color + "']");
				} else {
					$("#commentContent").val(content);
					packComment = $("#commentColorDiv").find("a[data-val='" + color + "']");
				}
				setCommentColor(packComment);
			},
			error: function () {
				$('#loading').modal('hide');
			}
		});
	} else {
		if (val == 1) {
			$("#commentContent1").val("");
			$("#commentColorFormGroup1").css("display", "none");
			setCommentColor($("#commentColorBtn1"));
		} else {
			$("#commentContent").val("");
			$("#commentColorFormGroup").css("display", "none");
			setCommentColor($("#commentColorBtn"));
		}
	}
};

/** 显示列表备注弹出框 **/
var showComment1 = function (packageId) {
	$('#commentContent1').val('');
	$('#commentPackageId').val(packageId);
	$('#commentType1').val('sys_picking');
	changeCommentColor($('#commentType1'), 1);
	$('#beizu1').modal('show');
	orderTemplateMethod($('#commentContent1'), 'sys_picking');
};

/**获取订单模板 **/
var orderTemplateMethod = function ($back, type) {
	MYJ.ajax({
		url: 'order/remark/config/getList.json',
		data: {
			type: type
		},
		loading: false,
		success: function (res) {
			var templateOrderArr = [{id: '', name: '请选择模板'}];
			if (!+res.code) {
				var allArr = res.data || [];

				for(var i = 0; i <allArr.length; i++) {
					templateOrderArr.push({
						id: allArr[i].id,
						name: allArr[i].remark,
						type: allArr[i].type,
						color: allArr[i].color
					})
				}
			}

			//注册模板
			$('.templateOrderRemark').selectMenu({
				data: templateOrderArr,
				valueKey: 'id',
				position: 'fixed',
				colorState: true,
				colorCall: function ($liMenu, j) {
					if (j.name && j.type) {
						if (j.type === 'sys_picking') $liMenu.prepend('<span class="bgCommentTagA inline-block" style="background: #' + j.color + '"></span>');
						$liMenu.append('<span class="del iconfont icon_delete delCommonSelData" title="删除"></span>');
					}
				},
				initCall: function () {
					$('.menuContentValueBox').val('').trigger('selectMenu:update');
				},
				clickCall: function (content, $iptObj, $menuListLi) {
					var name = $menuListLi.attr('data-name'),
						color = $menuListLi.attr('data-color'),
					     id = $menuListLi.attr('data-id');

                    if(id) {
						$back.val(name);
						setCommentColor($('a[data-val="' + color + '"]'));
					}
				},
				delDataCall: function (content, $contentIpt, $menuListLi) {
					var id = $menuListLi.attr('data-id');

					MYJ.ajax({
						url: 'order/remark/config/del.json',
						data: {
							id: id
						},
						success: function (res) {
							if (!+res.code) {
								MYJ.message.success('删除模板成功');
								$menuListLi.remove();
							} else {
								MYJ.message.error(res.msg);
							}
						}
					});
				}
			});
		}
	})
}

/** 增加备注 **/
var isAddCmt1 = false;
var addComment1 = function () {
	if (isAddCmt1) {
		return;
	}
	isAddCmt1 = true;
	var packageId = $("#commentPackageId").val();
	var commentType = $("#commentType1").val();
	var content = $.trim($('#commentContent1').val());
	var history = $("#keepState").data("history");
	if(!history) {
		history = "";
	}
	var color = $("#commentColorDiv1").find(".bgCommentFocus").attr("data-val");
	if ((content == null || content == '') && commentType == 'sys_service') {
		$.fn.message({type: "error", msg: "备注内容不能为空!"});
		isAddCmt1 = false;
		return;
	}
	if (content.length > 500) {
		$.fn.message({type: "error", msg: "备注内容长度不能超过500个字符!"});
		isAddCmt1 = false;
		return;
	}
	$.ajax({
		type: "POST",
		url: 'dxmPackageComment/add.json',
		data: {"packageId": packageId, "commentType": commentType, "content": content, "color": color, "history":history},
		dataType: "json",
		success: function (data) {
			isAddCmt1 = false;
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "备注信息增加成功!"});
				$('#beizu1').modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 执行批量更新拣货说明 **/
var executeBatchComment = function () {
	var $modal = $('#batchCommentInfo'),
		$loading = $('#loading'),
		type = $modal.attr('data-type'),
		url = '',
		history = $('#keepState').data('history');//区分历史订单和120天内订单

	if (!+type) {//批量拣货说明提交
		url = 'dxmPackageComment/batchUpdateComment.json';
	} else {//批量客服备注提交
		url = 'dxmPackageComment/batchAddServComment.json';
	}

	$loading.modal('show');
	$.ajax({
		type: 'POST',
		url: gitWinLocHref() + url,
		data: $('#batchCommentForm').serialize() + '&history=' + (history ? 'history' : ''),
		dataType: 'json',
		success: function (data) {
			$loading.modal('hide');
			if (!+data.code) {
				$modal.modal('hide');
				batchReturnProcess(data.bor.successList, data.bor.failList, '');
				refreshAjaxPage();
			} else {
				$.fn.message({type: 'error', msg: data.msg});
			}
			$modal = null;
			$loading = null;//释放内存
		},
		error: function () {
			$loading.modal('hide');
			$modal = null;
			$loading = null;//释放内存
		}
	});
};

/** 清空所有 **/
var clearComment = function () {
	$("#batchCommentTable").find("textarea").val("");
};

/** 弹出退款显示框 **/
var showRefund = function () {
    var platform = $("#platform").val();
    if(platform == 'wish'){
        $("#tuikuan").modal("show");
    }else if(platform == 'ebay'){
        $("#ebayTuikuan").modal("show");
    } else if (platform == 'lazada') {
		$("#lazadaTuikuan").modal("show");
	}
};

// 允许发货
var allowShipGoods = function (platform, id) {
	myjAlert.confirm({
		content: '允许发货为店小秘功能，与亚马逊后台无关联，请知悉',
		callback: function (v) {
			if (v) {
				$.ajax({
					type: "POST",
					async: false,
					url: '/order/allowShipGoods.json',
					data: {id: id},
					dataType: "json",
					success: function (data) {
						if (data.code === 0) {
							$.fn.message({type: "success", msg: data.msg});
							$("#allowShipGoods").addClass('hide');
							refreshAjaxPage();
						} else {
							$.fn.message({type: "error", msg: data.msg});
						}
					},
					error: function (re) {
						showNetError();
					}
				});
			}
		}
	});
};

/** 弹出转自发货的显示框 **/
var showSelfSendGoods = function(){
	var platform = $("#platform").val();
	if(platform == 'smt'){
		$("#smtTransferSelfSendGoods").modal("show");
	}
}

/*转自发货请求*/
var transferSelfSendGoodsConfirm = function () {
	var platform = $("#platform").val();
	//店小秘orderId
	var orderId = $("#orderId").val();
	if (platform != 'smt') {
		$.fn.message({type: "error", msg: "该平台订单不支持转自发货"});
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/transferSelfSendGoods.json',
		data: {"packageId": orderId},
		dataType: "json",
		success: function (data) {
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "订单转自发货成功!"});
				$("#smtTransferSelfSendGoods").modal('hide');
				$("#orderDetails").modal("hide");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			$('#loading').modal('hide');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
}

/** 退款订单 **/
var refundOrder = function () {
    var platform = $("#platform").val();
    var orderId = $("#orderId").val(),
        reasonCode,
		reasonNote,
		ebayReasonCode;
    if(platform == 'wish'){
    	reasonCode = $("#refundModal_reasonCode").val();
    	reasonNote = $.trim($("#refundModal_reasonNote").val());
        if (reasonCode == -1 && reasonNote == '') {
            $.fn.message({type: "error", msg: "请输入额外留言信息!"});
            return;
        }
        if (reasonNote.length > 250) {
            $.fn.message({type: "error", msg: "额外留言信息不能超过250个字符!"});
            return;
        }
    }else if(platform == 'ebay'){
        ebayReasonCode = $("#ebayReasonCode").val();
        if(ebayReasonCode == null || ebayReasonCode == ""){
            $.fn.message({type: "error", msg: "请选择退款理由!"});
            return;
		}
	} else if (platform == 'lazada') {
		reasonCode = $("#lazadaReasonCode").val();
		if (reasonCode == null || reasonCode == "") {
			$.fn.message({type: "error", msg: "请选择退款理由!"});
            return;
		}
	}
    $('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/refund.json',
		data: {
			"orderId": orderId,
			"reasonCode": reasonCode,
			"reasonNote": reasonNote,
			"ebayReasonCode": ebayReasonCode,
			"platform":platform
		},
		dataType: "json",
		success: function (data) {
            $('#loading').modal('hide');
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "订单退款成功!"});
				$("#tuikuan").modal("hide");
				$("#ebayTuikuan").modal("hide");
				$("#lazadaTuikuan").modal("hide");
				$("#orderDetails").modal("hide");
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 弹出解绑EPC显示框 **/
var showUnbindEPC = function (isMerge,isSplit) {
	if (isMerge) {
		$.fn.message({type: "error", msg: "合并订单不允许解绑，请拆分后再解绑"});
		return;
	}
	if (isSplit) {
		$.fn.message({type: "error", msg: "拆分订单不允许解绑，请合并后再解绑"});
		return;
	}
	$("#unbindEPC").modal("show");
};

/** 解绑EPC选择原因 **/
var unbindEPCSelect = function () {
	var reasonCode = $("#unbindEPCModal_reasonCode").val();
	if (reasonCode == 'OTHER') {
		$("#reasonNoteId").removeClass('hide');
	} else {
		$("#reasonNoteId").addClass('hide');
	}
};

/** 解绑EPC **/
var unbindEPC = function () {
	var orderId = $("#orderId").val(),
		reasonCode = $("#unbindEPCModal_reasonCode").val(),
		reasonNote = '';

	if (reasonCode == '-1') {
		$.fn.message({type: "error", msg: "请选择解绑原因!"});
		return;
	}
	if (reasonCode == 'OTHER') {
		reasonNote = $.trim($("#unbindEPC_reasonNote").val());
		if (reasonNote == '' || reasonNote == undefined) {
			$.fn.message({type: "error", msg: "请填写解绑理由!"});
			return;
		}
		if (reasonNote.length > 200) {
			$.fn.message({type: "error", msg: "解绑理由不能超过200个字符!"});
			return;
		}
	}

    $('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/unbindEPC.json',
		data: {
			"orderId": orderId,
			"reasonCode": reasonCode,
			"reasonNote": reasonNote
		},
		dataType: "json",
		success: function (data) {
            $('#loading').modal('hide');
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "解绑成功!"});
				$("#unbindEPC").modal("hide");
				$("#orderDetails").modal("hide");
				$("#packageDetailModal").modal("hide");
				refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
			showNetError();
		}
	});
};

/** 导出给货代 **/
var exportHd = function (state, templateId) {
	var url = "order/exportPackageOrder.json?templateId=" + templateId + "&state=" + state,
		$shopGroupId = $('#shopGroupId'),
		pageTag = $('#pageTag').val(),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	if (pageTag) url += '&requestLocation=' + pageTag;//如果页面有pageTag内容，则需要传给后端做导出
    confirmModel("", templateId, url, "", null, 2);
};

/** 显示导出勾选项和导出所有页 **/
var showExcelSelectAndAll = function (isAll, state) {
	var merged = $("#merged").val();
	var splited = $("#splited").val();
	$("#exportPayTime").hide();
	if (isAll == 0) {
		var packageIds = "";
		if(merged == "merged" || splited == "splited"){
			$("td input[mergedname='mergedName']:checked").each(function() {
				var v = $(this).val();
				if(packageIds != ""){
					packageIds = packageIds + ",";
				}
				packageIds = packageIds + v;
			});
		}else {
			packageIds = getCheckBoxValByName("packageId");
		}
		$("#exportOrderBtn").attr("onclick", "exportSelectPackage(this);");
	} else {
		$("#exportOrderBtn").attr("onclick", "exportAllPackage(this);");
	}
	$("#exportState").hide();
	$("#exportSelectAll").hide();
	$('.exportTimeTip').addClass('hide');
	$("#exportSelectAll").find("input").prop("checked", true);
	$("#exportTable").hide();
	$("#exportTable").find('table.excl td').html("");

	getTemplate("order");
	$('#exportModel input[name="isMaster"]').prop('checked',false);
	$('#exportModel input[cid="isMaster"]').prop('checked',true);
	$("#exportModel").modal("show").find('#exportOrderBtn').attr('data-all',isAll);
};

/** 显示导出勾选项和导出所有页 **/
var showImportExcelSelectAndAll = function (state) {
    $('#importTrackNumberFileName, #importTypeSpan').empty();
    $('#importTemplateHref').addClass('hide');
    $('#importTemplateSelect').val('0');

    $('#importModel').modal('show');
	importTrackNumUp.cancel('*');
};

/** 导出勾选项包裹中的订单 **/
var exportSelectPackage = function (obj) {
	var merged = $("#merged").val();
	var splited = $("#splited").val();
	var packageIds = '';
    if(merged === 'merged' || splited === 'splited'){
		$("td input[mergedname='mergedName']:checked").each(function() {
			var v = $(this).val();
            if(packageIds !== ''){
				packageIds = packageIds + ',';
			}
			packageIds = packageIds + v;
		});
	}else {
		packageIds = getCheckBoxValByName('packageId');

	}
	if (packageIds === '') {
		$.fn.message({type: "error", msg: "请至少选择一个包裹"});
		return;
	}
	var arr = '';
	var templateId = $("#exportTemplateSelect").val();
    var isMaster= $('#exportModel').find('input[name="isMaster"]:checked ').val();
    if (+templateId === -1 || +templateId === -2) { // 标准模板
		arr = exportDataGetNew('exportModel');
	} else if (templateId > 0) {
		arr = dataGetNew('exportModel'); // 自定义模板
	} else {
		$.fn.message({type: "error", msg: "请选择模板类型!"});
		return;
	}
	var exportKeys = formatFieldFromArrayToString(arr);
    if (exportKeys === '') {
		$.fn.message({type: "error", msg: "您没有选择导出任何选项，请选择后再操作!"});
		return;
	}
	var history = $("#keepState").data("history");
	if(!history) history = '';
	// isMaster 0 订单维度 1 包裹维度 2 产品维度
	var url = "order/exportPackageOrder.json?exportStyle="+isMaster+"&history="+history,
		$shopGroupId = $('#shopGroupId'),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '',
		pageTag = $('#pageTag').val();

	if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	if (pageTag) url += '&requestLocation=' + pageTag;//如果页面有pageTag内容，则需要传给后端做导出
	confirmModel(exportKeys, templateId, url, packageIds, obj, 0);
};
//  判断同一个用户是不是已经有导出订单任务正在进行中
var confirmModel = function(exportKeys, templateId, url, packageIds, obj, type) {
    $.ajax({
        type: "GET",
        url: "/order/checkExportPackageBusy.json",
        data: {},
        dataType: "json",
        async: false,
        success: function (data) {
            if (data.code == 0){
                if (data.flag) {
                    var isAll = $(obj) && $(obj).attr('data-all');
                    // // 如果已经有订单正在导出，则弹出一个确认框让用户确认
                    $("#userConfirmBreakExportModal").modal('show')
                        .find('#userConfirmBreakExport').attr({
                        'data-key':exportKeys,
                        'data-tempId':templateId,
                        'data-url':url,
                        'data-all':isAll,
						'data-packageIds' : packageIds,
						"data-type" : type
                    });
                } else {
                    batchExportOrder(exportKeys, templateId, url, packageIds);
                }
            }
        }
    })
};

/** 导出所有包裹订单 **/
var exportAllPackage = function (obj) {
	var $keepState = $('#keepState'),
		state = $keepState.data("state"),
		authId = $keepState.data("authid"),
		shopId = $keepState.data("shopid"),
		platform = $keepState.data("platform"),
		isSearchState = +($keepState.data('selecttype')) === 2;//如果是2，则是搜索类型，发货时间这些是不需要传的

	if(platform == undefined) platform = "";

	var startTime = $keepState.data("starttime"),
		endTime = $keepState.data("endtime"),
		country = $keepState.data("country"),
		commitPlatform = $keepState.data("commitplatform"),
		searchType = $keepState.data("searchtype");

	if(searchType == undefined || searchType === '') searchType = "orderId";
	var isRemoved = $keepState.data("isremoved");
	if (isRemoved == undefined) isRemoved = "0";
	var content = $("#searchContent").val();	// 搜索内容
	var isVoided = $keepState.data("isvoided");
	isVoided = isVoided || 0;
	if (country == undefined) {
		country = "";
	}
    var custom = $("#keepState").data("custom");
    var printJh = $("#keepState").data("printjh");
    if (printJh == undefined) {
        printJh = "-1";
    }
    var printMd = $("#keepState").data("printmd");
    if (printMd == undefined) {
        printMd = "-1";
    }
    var productStatus = $("#keepState").data("productstatus");
    var storageId = $("#keepState").data("storageid");
    if (storageId == undefined || storageId == "") {
        storageId = 0;
    }
    var jhComment = $("#keepState").data("jhcomment");

	var isMaster= $('#exportModel input[name="isMaster"]:checked ').val();
    var orderField = $("#keepState").data("orderfiled");
    if (orderField == undefined) {
        orderField = "";
    }
    var isSearch = $("#keepState").data("search");
    if (isSearch == undefined || isSearch == '') {
        isSearch = "0";
    }
    var ruleId = $("#keepState").data("ruleid");
    if (ruleId == undefined) {
        ruleId = "-1";
    }
    var sysRule = $("#keepState").data("sysrule");
    if (sysRule == undefined) {
        sysRule = "";
    }
    var behindTrack = getBehindState();
	var arr = "";
	var templateId = $("#exportTemplateSelect").val();
	if (+templateId === -1 || +templateId === -2) {
		arr = exportDataGetNew('exportModel');	 // 标准模板
	} else if (templateId > 0) {
		arr = dataGetNew('exportModel'); // 自定义模板
	} else {
		$.fn.message({type: "error", msg: "请选择模板类型!"});
		return;
	}
	var exportKeys = formatFieldFromArrayToString(arr);
	if (exportKeys == '') {
		$.fn.message({type: "error", msg: "您没有选择导出任何选项，请选择后再操作!"});
		return;
	}
    var forbiddenStatus = '-1';
    var newVersion = $('#newVersion').val();
    if (+newVersion == 1 && state == 'allocated_has') {
        forbiddenStatus = $keepState.data("forbiddenstatus");
    }
	exportKeys = encodeURIComponent(exportKeys);
	var isOversea = $keepState.data("isoversea");
	var applyStatus = $keepState.data("applystatus");
	if(content !== '') applyStatus = '';
	var history = $keepState.data("history");
	if(!history) history = '';
	var isAdvanced = $("#isAdvanced").val(),
        url = '',
		$shopGroupId = $('#shopGroupId'),
		pageTag = $('#pageTag').val(),
		shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if(isAdvanced == 1){ // 高级搜索导出
		url = "order/exportPackageOrderAdvanced.json?exportKeys="+exportKeys+"&templateId="+templateId+"&exportStyle="+isMaster
			+"&history="+history+"&orderField="+orderField+"&isSearch="+isSearch;

		//如果是发货失败，则behindTrack写死99
		if (state === 'shipped' && commitPlatform === 'fail') {
			url += '&behindTrack=99'; //behindTrack写死99，behindTrack=发货订单\待补录订单tab切换的状态
		} else {
			url += '&behindTrack=' + behindTrack;
		}
		if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
		if (pageTag) url += '&requestLocation=' + pageTag;//如果页面有pageTag内容，则需要传给后端做导出
		batchExportOrderAdvanced(exportKeys, templateId, url);
	} else {
		var isGreen = "";
		var isYellow = "";
		var isOrange = "";
		var isRed = "";
		var isViolet = "";
		var isBlue = "";
        var cornflowerBlue = "";
        var pink = "";
        var teal = "";
        var turquoise = "";
        var unmarked = "";

		$('#customCommentSearchDiv span.module').each(function () {
			var uid = $(this).attr('uid');
			var dataType = $(this).data('type');
			if(uid === "moduleA") isGreen = dataType;
			if(uid === "moduleB") isYellow = dataType;
			if(uid === "moduleC") isOrange = dataType;
			if(uid === "moduleD") isRed = dataType;
			if(uid === "moduleE") isViolet = dataType;
			if(uid === "moduleF") isBlue = dataType;
            if(uid === "moduleW") cornflowerBlue = dataType;
            if(uid === "moduleX") pink = dataType;
            if(uid === "moduleY") teal = dataType;
            if(uid === "moduleZ") turquoise = dataType;
            if(uid === "moduleI") unmarked = dataType;
		});

		$("#advancedTemplateId").val("");
		$("#advancedExportKeys").val("");
		var orderSearchType = $("#orderSearchType").val(),
			timeStr = isSearchState ? '' : '&startTime=' + startTime + '&endTime=' + endTime;
		url = "order/exportPackageOrder.json?state=" + state + "&authId=" + authId + "&shopId=" + shopId + "&country=" + country + timeStr
			+ "&platform="+platform+"&exportStyle="+isMaster+ "&searchType=" + searchType + "&content=" + content + "&isVoided=" + isVoided + "&commitPlatform="+commitPlatform+"&isOversea="+isOversea+
			"&applyStatus="+applyStatus+"&isGreen=" + isGreen + "&isYellow=" + isYellow + "&isOrange=" + isOrange + "&isRed=" + isRed + "&isViolet=" + isViolet + "&isBlue=" + isBlue + "&cornflowerBlue=" + cornflowerBlue
			+ "&pink=" + pink + "&teal=" + teal + "&turquoise=" + turquoise+"&unmarked=" + unmarked + "&isRemoved="+isRemoved+"&history="+history+"&custom="+custom+'&printJh='+printJh+'&printMd='+printMd+"&productStatus="+productStatus
			+"&storageId="+storageId+"&jhComment="+jhComment+"&orderField="+orderField+"&isSearch="+isSearch+"&ruleId="+ruleId+"&sysRule="+sysRule + "&forbiddenStatus="+forbiddenStatus +"&behindTrack="+behindTrack+"&orderSearchType="+orderSearchType,
			$shopGroupId = $('#shopGroupId'),
			shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

		if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
		if (pageTag) url += '&requestLocation=' + pageTag;//如果页面有pageTag内容，则需要传给后端做导出
		//  判断同一个用户是不是已经有导出订单任务正在进行中
        confirmModel(exportKeys, templateId, url, "", obj, 0);
	}
};


/** 判断同一个用户是不是已经有导出订单任务正在进行中*/
var confirmBreak = function (obj,flag) {
	$('#userConfirmBreakExportModal').modal('hide');
	var $obj = $(obj);
	// 点击确定
	if(flag){
        var key = $obj.attr('data-key'),
            tempId = $obj.attr('data-tempId'),
            url = $obj.attr('data-url'),
        	packageIds = $obj.attr("data-packageIds");
        batchExportOrder(key, tempId, url, packageIds);
	}else{ // 取消，回到原页面
		var isAll = $('#userConfirmBreakExport').attr('data-all');
		var type = $('#userConfirmBreakExport').attr("data-type");
		if (type == 0) {
			showExcelSelectAndAll(+isAll,'paid');
		} else if (type == 1) {
			showExportModal('order');
		} else if (type == 2) {
            // 导出给货代的自然取消即可
		}
	}
};

/** 得到重新发货订单ID **/
var getReShipOrderId = function (orderId, orderIdPlat) {
	$.ajax({
		type: "POST",
		url: 'package/getReShipOrderId.json',
		data: {"orderId": orderId},
		dataType: "json",
		success: function (data) {
			var orderIdStr = data.orderIdStr;
			if (orderIdStr == '') {
				orderIdStr = orderIdPlat + "-1";
			}
			$("#reShippedOrderTd").html(orderIdStr);
		}
	});
};

/** 执行重新发货 **/
var reShipped = function () {
	var orderIdStr = $("#reShippedOrderTd").text();
	var skus = $("input[name='skus']");
	var orderNums = $("input[name='orderNums']");
	var prices = $("input[name='prices']");
	var reg = /^\d+(\.\d{1,2})?$/;
	var a = validateCustom(skus, "", 0, "请输入产品SKU");
	if (a) {
		return;
	}
	var b = validateCustom(orderNums, /^[0-9]*$/, 1, "请输入数量", "数量请输入大于0的整数");
	if (b) {
		return;
	}
	var c = validateCustom(prices, reg, 3, "请输入单价", "单价请输入大于0的数字,小数点保留1-2位");
	if (c) {
		return;
	}
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'order/reShipped.json',
		data: $("#reShippedForm").serialize(),
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			var code = data.code;
			if (code == 0) {
				$.fn.message({type: "success", msg: "新建订单成功！订单" + orderIdStr + " 已创建到「待处理」"});
				closePackageReShipped();
			} else {
				$.fn.message({type: "error", msg: data.msg});
				$("#trackingError").html(data.msg);
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 关闭包裹重新发货弹层 **/
var closePackageReShipped = function () {
	$("#reShipments").modal("hide");
	$("#packageDetailModal").modal("hide");
	$("#packageDetailModal").modal("show");
};

/** 增加商品 **/
var addProduct = function () {
	var str = '<tr><td><input type="text" class="form-control" name="skus"/></td><td><input type="text" class="form-control" name="orderNums"/></td><td><input type="text" class="form-control" name="prices"/></td><td><a href="javascript:" onclick="delProduct(this);">删除</a></td></tr>';
	$("#reShippedTable").append(str);
};

/** 删除商品 **/
var delProduct = function (obj) {
	$(obj).parent().parent().empty();
};

//修改物流信息时改变物流方式，物流追踪号置为空
var reShippedSelectProvider = function () {
	var agentType = $("#reShippedSelect option:selected").attr("agentype");
	var allotType = $("#reShippedSelect option:selected").attr("allotType");
	if (agentType == 2 || agentType == -1) {
		// 系统对接
		$("#reShippedTrackDiv").html("自动获取");
	} else {
		if (allotType == 1) {
			$("#reShippedTrackDiv").html("号码池分配");
		} else {
			$("#reShippedTrackDiv").html("手动上传");
		}
	}
};



var productSkuObj = '';

//获取要选择的商品
var ajaxGetStockProduct = function (isAdd) {
	var $loading = $('#loading');
	$loading.modal('show');
	$.ajax({
		type: "POST",
		url: "dxmCommodityProduct/getProductsOrderTwoPageList.htm",
		data: {"isAdd": isAdd},
		dataType: "html",
		success: function (data) {
			$loading.modal('hide');
			$('#selectProductsOrderPageList').html(data);
			$("div.quoteImgDivIn").picZoom({
				imgWidth: "296",
				imgHeight: "296",
				divWidth: "300",
				divHeight:"300"
			});
		},
		error: function () {
			showNetError();
			$loading.modal('hide');
		}
	});
};

/************* 重新发货 ************/
var reShipProductObj = '';
var reShipProductSelect = function (obj) {
	$("#productsOrderQuoteModal").modal("show");
	reShipProductObj = obj;
	ajaxGetStockProduct(0);
};
/************* 重新发货 ************/

/** 字段SKU库存 **/
var showDialogWareHoseProduct = function (orderId, num, ztStatus, isAdd, isGift, obj) {
	$('#loading').modal('show');
	var isEditState = $('#isEditState').val(),
		platform =  $('#platform').val(),
        $whpqm = $("#wareHoseProductsQuoteModal");

	if(isEditState != 'save'){
		$.fn.message({type: "error", msg: "请先保存物流信息，再进行配对操作！"});
        $('#loading').modal('hide');
        return;
	}
	// 礼品选择列表 & 商品选择列表 弹层标题关键词切换
	if(isGift == 1){
		$whpqm.find(".customModalHead .mainCon").html("礼品搜索");
		$whpqm.find(".searchTerm").html("礼品SKU");
	}else if(isGift == 2){
		$whpqm.find(".customModalHead .mainCon").html("商品搜索");
		$whpqm.find(".searchTerm").html("商品SKU");
	}
    $('#packageDetailModal').modal('hide');

    placementInfoElasticLayer(obj, $whpqm, 'order'); //弹层放置产品信息

    $whpqm.customModal("show");
	$("#closeInIdentifyNoModalBtn").attr("onclick","closeInIdentifyNoQuoteModal();");
	ajaxGetProducts(orderId, num, ztStatus, isAdd, isGift);
};

//获取要选择的商品
var ajaxGetProducts = function (orderId, num, orderStatus, isAdd, isGift) {
	$('#selectWareHoseProductsPageList').html('');
	var hidId = "#relationHidden_" + orderId + "_" + num;
	var vid = $(hidId).attr("vid"),
		platId = $(hidId).attr("pid"),
		packageId = $(hidId).attr("packageid"),
		pt = $(hidId).attr("platform"),
		shopId = $(hidId).attr("shopid"),
		relationHiddenCurrId = $(hidId).attr("currid"),
		orderCount = $(hidId).attr("count"),
		relationHiddenWarehoseId = $(hidId).attr("warehoseid");

	var ovAuthId     = $("#updateShipInfoAuthSelect option:selected").attr("overauthid");
	if(ovAuthId == undefined){
		ovAuthId = "";
	}
	var ovWarehoseId = $("#updateShipInfoAuthSelect option:selected").attr("overwareid");
	if(ovWarehoseId == undefined){
		ovWarehoseId = "";
	}
	if(isAdd == undefined || isAdd == ''){
		isAdd = 0;
	}
	//测试数据
	var data = getProductsOrderPageListData();
	$('#loading').modal('hide');
	$('#selectWareHoseProductsPageList').html(data);
	return;
	$.ajax({
		type: "POST",
		url: "dxmCommodityProduct/getProductsOrderPageList.htm",
		data: {
			"pageNo": 1,
			"pid": platId,
			"vid": vid,
			"pt": pt,
			"shopId": shopId,
			"packageId": packageId,
			"orderId": orderId,
			"poRelationId": relationHiddenCurrId,
			"orderStatus": orderStatus,
			"orderCount": orderCount,
			"orderWarehoseId": relationHiddenWarehoseId,
			"ovAuthId" : ovAuthId,
			"ovWarehoseId" : ovWarehoseId,
			"platform":$('#platform').val(),
			"isAdd" : isAdd,
			"isGift" : isGift		// 1、查询礼品列表		2、查询售卖品列表
		},
		dataType: "html",
		success: function (data) {
			$('#loading').modal('hide');
			$('#selectWareHoseProductsPageList').html(data);
		}
	});
};

/** 订单列表进行配对 **/
var showDialogWareHoseProductList = function (orderId, num, ztStatus, isOversea, authId, obj) {
	// 礼品选择列表 & 商品选择列表 弹层标题关键词切换
	var $whpqm = $("#wareHoseProductsQuoteModal");
	$whpqm.find("h4").html("商品搜索");
	$whpqm.find(".pTop10").find("a:eq(0)").html("商品SKU");
    $whpqm.find('#searchWareHoseProductsValue').val('');
    $whpqm.find('.proQuoteType').val('list');

    placementInfoElasticLayer(obj, $whpqm, 'list'); //弹层放置产品信息

	$whpqm.customModal("show");
	$("#closeInIdentifyNoModalBtn").attr("onclick","");

	var hidId = "#relationListHidden_" + orderId + "_" + num;
	var vid = $(hidId).attr("vid"),
		platId = $(hidId).attr("pid"),
		packageId = $(hidId).attr("packageid"),
		pt = $(hidId).attr("platform"),
		shopId = $(hidId).attr("shopid"),
		poRelationId = $(hidId).attr("currid"),
		orderCount = $(hidId).attr("count"),
		warehoseId = $(hidId).attr("warehoseid");
	if(poRelationId == undefined){
		poRelationId = "";
	}
	if(isOversea == 1){
		// 如果是海外仓
		$.ajax({
			type: "POST",
			url: "agent/getByAuthId.json",
			data: {
				"authId": authId
			},
			dataType: "json",
			success: function (data) {
				ajaxGetProductList(platId, vid, pt, shopId, packageId, orderId, poRelationId, ztStatus, orderCount, warehoseId, data.ovAuthId, data.ovWarehoseId, data.platform);
			}
		});
	} else {
		ajaxGetProductList(platId, vid, pt, shopId, packageId, orderId, poRelationId, ztStatus, orderCount, warehoseId, '', '', '');
	}
};

/** 订单列表配对查询商品列表 **/
var ajaxGetProductList = function (pid, vid, pt, shopId, packId, orderId, poRelationId, orderStatus,
								   orderCount, orderWarehoseId, ovAuthId, ovWarehoseId, platform) {
	$('#selectWareHoseProductsPageList').html('');
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: "dxmCommodityProduct/getProductsOrderPageList.htm",
		data: {
			"pageNo": 1,
            "pageSize": 50,
			"pid": pid,
			"vid": vid,
			"pt": pt,
			"shopId": shopId,
			"packageId": packId,
			"orderId": orderId,
			"poRelationId": poRelationId,
			"orderStatus": orderStatus,
			"orderCount": orderCount,
			"orderWarehoseId": orderWarehoseId,
			"ovAuthId" : ovAuthId,
			"ovWarehoseId" : ovWarehoseId,
			"platform": platform,
			"isAdd" : 0,
			"isGift" : 2,		// 1、查询礼品列表		2、查询售卖品列表
			"isList" : "1"
		},
		dataType: "html",
		success: function (data) {
			$('#loading').modal('hide');
			$('#selectWareHoseProductsPageList').html(data);
		}
	});
};

var placementInfoElasticLayer = function(obj, modal, type){  //弹层放置产品信息
   var $proOut = '',
	   $whpqm = $(modal);
   switch (type) {
	   case 'list':
		   $proOut = $(obj).closest('.pairProInfo');
		   break;
	   case 'order':
		   $proOut = $(obj).closest('.pairProInfoBox').find('.pairProInfo');
		   break;
	   case 'lookOccupy':
		   $proOut = $(obj);
		   $whpqm.find(".customModalHead .mainCon").html("商品搜索");
		   $whpqm.find(".searchTerm").html("商品SKU");
		   break;
   }
   var imgUrl = $proOut.find('.pairProInfoImg').attr('src'),
       proSku = $proOut.find('.pairProInfoSku').text(),
       $proName = $proOut.find('.pairProInfoName');

	$whpqm.find('#modalSkuId').addClass('tab-active');
	$whpqm.find('#modalSkuCodeId').removeClass('tab-active');
	$whpqm.find('#modalSkuNameId').removeClass('tab-active');
	$whpqm.find('#searchWareHoseProductsType').val(1);
    $whpqm.find('#searchWareHoseProductsValue').val('');
	var locHref = gitWinLocHref();
    $whpqm.find('.pairProInfoImg').attr('src',imgUrl ? imgUrl : locHref +"static/img/kong.png");
    $whpqm.find('.pairProInfoSku').text($.trim(proSku) );
    $whpqm.find('.pairProInfoName').html('');
    if($proName && $proName.length > 0){
    	var proNameStr = [];
    	$.each($proName, function (i,j) {
    		proNameStr.push($('<p></p>').text($(j).text()));
        });
        $whpqm.find('.pairProInfoName').html(proNameStr);
    }
};

var closeInIdentifyNoQuoteModal = function () {
	var $modal = $('#wareHoseProductsQuoteModal'),
	     type = $modal.find('.proQuoteType').val();

    $modal.find('.proQuoteType').val('');
    $modal.customModal('hide');
    if(!(type === 'list')) $('#packageDetailModal').modal('show');
};

//解除关系确认框
var trueOrFalseRemoveRelation = function (orderId, num, status) {
	var pid = $("#relationHidden_"+ orderId + "_" + num).attr("pid");
	var productId = $("#relationHidden_"+ orderId + "_" + num).attr("proid");
	$("#relationHiddenPid").val(pid);
	$("#relationHiddenOrderId").val(orderId);
	$("#relationHiddenNum").val(num);
	$("#relationHiddenProductId").val(productId);
	$("#relationHiddenStatusId").val(status);
	var isPriorShip = false;
	if($("#signPriorValue").val() == 'true'){ //判断是否标记优先发货
		isPriorShip = true;
	}

	var matchNum = 0; //配对SKU个数
	$("input[name='relationProductId']").each(function () {
		var proId = $(this).val();
		if(proId != "" && proId != undefined){
			matchNum++;
		}
	});
	$("#matchProNum").val(matchNum);
	if (status == 'approved' || status == 'paid') {
		if(isPriorShip && matchNum == 1){
			$("#relationSignPrior").css("display","block");
		}
		$('#warningRemoveRelationModel').modal('show');
	} else {
		if(isPriorShip  && matchNum == 1){
			$("#currRelationSignPrior").css("display","block");
		}
		$('#warningRemoveCurrRelationModel').modal('show');
	}
};

//不解除
var falseRemoveProductRelation = function () {
	$('#warningRemoveRelationModel').modal('hide');
    $('#packageDetailModal').modal('hide');
    $('#packageDetailModal').modal('show');
};

//解除库存sku
var removeProductRelationFlag = false;
var removeProductRelation = function () {
	if(removeProductRelationFlag){
		return;
	}
	removeProductRelationFlag = true;
	var pid = $("#relationHiddenPid").val(),
		orderId = $("#relationHiddenOrderId").val(),
		num = $("#relationHiddenNum").val(),
		productId = $("#relationHiddenProductId").val(),
		orderStatus = $("#relationHiddenStatusId").val();

	var hidId = "#relationHidden_" + orderId + "_" + num;
	var vid = $(hidId).attr("vid");
	var pt = $(hidId).attr("platform");
	var packageId = $(hidId).attr("packageid");
	var shopId = $(hidId).attr("shopid");
	var warehoseId = $(hidId).attr("warehoseid");
	var relationHiddenCurrId = $(hidId).attr("currid");
	var count = $(hidId).attr("count");
	var warningRemoveRelation = $("input[name='warningRemoveRelation']:checked").val();
	var matchProNum = $("#matchProNum").val(); //已配对商品sku个数
	var isPrior = $("#signPriorValue").val();
	var cancelPriorShip = 0;
	if(matchProNum == 1 && isPrior == 'true'){
		cancelPriorShip = 1;
	}
	if (orderStatus == 'approved' || orderStatus == 'paid') {
	} else {
		warningRemoveRelation = 0;
	}
	$.ajax({
		type: "POST",
		url: "dxmCommodityProduct/removeRelationForOrder.json",
		data: {
			"pid": pid,
			"vid": vid,
			"shopId": shopId,
			"pt": pt,
			"orderId": orderId,
			"num": count,
			"productId": productId,
			"warningRemoveRelation": warningRemoveRelation,
			"orderStatus": orderStatus,
			"orderWarehoseId": warehoseId,
			"poRelationId": relationHiddenCurrId,
			"cancelPriorShip":cancelPriorShip
		},
		dataType: "json",
		success: function (data) {
			if (data.code > 0) {
				$.fn.message({type: "success", msg: "映射关系解除成功！"});
				dxmPackageDetail(packageId);
			} else {
				$.fn.message({type: "error", msg: "映射关系解除失败！"});
			}
			removeProductRelationFlag = false;
		}
	});
};

//获取仓库值
var ajaxWarehoses = function (storageId,isOversea,overseaName) {
	$("#orderPackageStockId").children().remove();
	$.ajax({
		type: "GET",
		url: "dxmWarehoseCon/getWarehosesForOrder.json",
		data: {},
		dataType: "json",
		success: function (data) {
			if (data != "") {
				$.each(data, function (index, value) {
					if (index == 0) {
						if (storageId == value.id) {
							var optionX = "<option value='" + value.id + "' selected>" + value.name + "</option>";
							$("#orderPackageStockSelectId").append($(optionX));
						} else {
							var optionX = "<option value='" + value.id + "'>" + value.name + "</option>";
							$("#orderPackageStockSelectId").append($(optionX));
						}
					} else {
						if (storageId == value.id) {
							var optionX = "<option value='" + value.id + "' selected>" + value.name + "</option>";
							$("#orderPackageStockSelectId option").last().after(optionX);
						} else {
							var optionX = "<option value='" + value.id + "'>" + value.name + "</option>";
							$("#orderPackageStockSelectId option").last().after(optionX);
						}
					}
				});
				// 海外仓
				if(isOversea == 1){
					$("#orderPackageStockSpan").html(overseaName);
					$("#orderPackageStockSpan").css("display","");
					$("#orderPackageStockSelectId").css("display","none");
				} else {
					$("#orderPackageStockSpan").text("");
					$("#orderPackageStockSpan").css("display","none");
					$("#orderPackageStockSelectId").css("display","");
				}
			}
		}
	});
};

//仓库切换函数,将仓库数据保存到订单中
var orderPackageStockSelectChange = function (packageId) {
	var pidArr = [];
	$.each($("input[id^=relationHiddenProductId_]"), function (index, val) {
		pidArr.push($(this).val());
	});
	$.ajax({
		type: "POST",
		url: 'package/saveStorageIdForOrder.json',
		data: {
			"packageId": packageId,
			"storageId": $("#orderPackageStockSelectId").val(),
			"pids": pidArr.join(",")
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "仓库保存成功！"});
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			dxmPackageDetail(packageId);
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

//修改订单仓库值
var updateChangeRelationWareHose = function () {
	var changeRelationWareHose = $("input[name='changeRelationWareHose']:checked").val();
	var packageId = $("#confirmChangeRelationWareHoseHiddenId").val();
	var wareHouse = $("#orderPackageStockSelectId").val();
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/saveStorageIdForOrder.json',
		data: {
			"packageId": packageId,
			"storageId": $("#orderPackageStockSelectId").val(),
			"changeRelationWareHose": changeRelationWareHose
		},
		dataType: "json",
		success: function (data) {
			$('#loading').modal('hide');
			$("#orderPackageStockSelectId").find('option[value = '+wareHouse+']').prop('selected', true);
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "仓库保存成功！"});
				dxmPackageDetail(packageId);
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};

/** 发消息详情页 **/
var sendMsgDetail = function (packageId, platform) {
    var $replyMessageModal = $('#replyMessageModal');

	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'replyMsg/detail.json',
		data: {'packageId': packageId},
		dataType: "html",
		success: function (data) {
			$('#loading').modal('hide');
            $replyMessageModal.html(data).modal("show");
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};
/** 发送消息 **/
var sendMsg = function (platform) {
	var content = $.trim($("#replyContent").val());
	if (content == "") {
		$.fn.message({type: "error", msg: "请输入回复内容！"});
		return;
	}
    if(platform == 'smt'){
        //判断只能插入一张图片
        var imgNum = $("#importPicName img.imgCss").length;
        if(imgNum > 1){
            $.fn.message({type:"error",msg:"只可插入一张图片！"});
            return;
        }
        if (content.length > 1000) {
            $.fn.message({type: "error", msg: "长度不能超过1000个字符！"});
            return;
        }
    }else{
        if (content.length > 4000) {
            $.fn.message({type: "error", msg: "长度不能超过4000个字符！"});
            return;
        }
    }
    if(platform !== 'ebay' && /.*[\u4e00-\u9fa5]+.*$/.test(content)){
        $.fn.message({type:"error", msg:"内容中不能包含中文，请重新编写！"});
        return;
    }
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'replyMsg/reply.json',
		data: $("#sendMessageForm").serialize(),
		dataType: "json",
		success: function (data) {
			if (data.code == 0) {
				$.fn.message({type: "success", msg: "消息发送成功！"});
				$("#replyMessageModal").modal("hide");
                refreshAjaxPage();
			} else {
				$.fn.message({type: "error", msg: data.msg});
			}
			$('#loading').modal('hide');
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};
/**************ebay上传图片start**************/
// 显示从空间选择图片的窗口
function showImgSpaceFrame() {
	$("#myFrame").attr("src", 'album/selectImg.htm');
	$('#loading').modal('show');
}
/** 关闭图片选择框 **/
var closeSelectImg = function () {
	$("#selectImgFromSpace").modal("hide");
	$("#replyMessageModal").modal("hide");
	$("#replyMessageModal").modal("show");
};
//主图调用
function hideImgSpaceFrame() {
	$('#loading').modal('hide');
	$("#selectImgFromSpace").modal("show");
}

/** 选择从图片空间选择的图片 **/
var selectImgFromSpace = function (shopId) {
	var imgIds = document.getElementById('myFrame').contentWindow.getSelectImgId();
	$('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'ebayMessage/uploadPic.json',
		data: {"shopId": shopId, "imgIds": imgIds},
		dataType: "json",
		success: function (data) {
			var list = data.list;
			if (list != null) {
				for (var i = 0; i < list.length; i++) {
					var album = list[i];
					var picStr = getPicStr(album.imgUrl, album.idStr);
					$("#importPicName").append(picStr);
				}
			}
			$('#loading').modal('hide');
			closeSelectImg();
		},
		error: function () {
			$('#loading').modal('hide');
		}
	});
};
/** 显示选中的图片 **/
var getPicStr = function (picUrl, imgId) {
	var str = '<div class="p5 pull-left imgHomeSm ui-sortable-handle">' +
		'<a class="aMakeRemoveBtn closeBadge" style="z-index:100;"></a>' +
		'<div class="imgDivIn" style="width:50px;height:50px;">' +
		'<img src="' + picUrl + '" class="imgCss" />' +
		'<input type="hidden" name="imgId" value="' + imgId + '"/>' +
		'</div>' +
		'</div>';
	return str;
};
/******************** ebay上传图片end*********************/
$(document).on('click', '.closeBadge', function () {
	var div = $(this).closest('div.imgHomeSm');
	$(div).remove();
});



// 订单自定义标记
(function($,doc){
	var selHtml = '<div class="signDropdown">' +
		'<div class="tit">自定义标记</div>' +
		'<div class="cont">' +
		'<ul></ul>' +
		'<div class="explain"><span>说明！</span>筛选标记，请使用搜索</div>' +
		'</div>' +
		'<div class="btnGroup"><button class="button btn-determine" type="button" uid="enter">确定</button><button class="button btn-gray m-left10" type="button" uid="cancel">取消</button></div>' +
		'</div>';
	var selLiHtml = '<li><a href="javascript:" class="signCont" data-type="0"><span class="glyphicon glyphicon-ok signState myj-hide"></span><span class="inline-block w-full no-new-line signContent">无描述</span></a><a href="javascript:" class="signEdit" title="编辑" uid="operation" nowType="0"></a></li>';
	var selSignHtml = '<span class="glyphicon glyphicon-ok"></span>';
	// 下拉框改标记值统一方法
	var signIptEnter = function(obj, moduleName, ipt){
		var customSign = $(obj).closest('.custom-sign-myj');
		var operationBtn = ipt.closest('li').find('a[uid="operation"]');
		var iptVal = $.trim(ipt.val());
		if(iptVal){
			ipt.closest('li').find('.signContent').text(iptVal).attr('title', iptVal);
		} else {
			ipt.closest('li').find('.signContent').text('无描述').attr('title', '无描述');
		}
		if (moduleName == "moduleA"){
			contentType = 'isGreen';
		}
		if (moduleName == "moduleB"){
			contentType = 'isYellow';
		}
		if (moduleName == "moduleC"){
			contentType = 'isOrange';
		}
		if (moduleName == "moduleD"){
			contentType = 'isRed';
		}
		if (moduleName == "moduleE"){
			contentType = 'isViolet';
		}
		if (moduleName == "moduleF"){
			contentType = 'isBlue';
		}
        if (moduleName == "moduleW"){
            contentType = 'cornflowerBlue';
        }
        if (moduleName == "moduleX"){
            contentType = 'pink';
        }
        if (moduleName == "moduleY"){
            contentType = 'teal';
        }
        if (moduleName == "moduleZ"){
            contentType = 'turquoise';
        }

		$.ajax({
			type: "POST",
			url: "/package/updateOrderUserSingleContent.json",
			data: { "contentType": contentType,
				"content": iptVal},
			dataType: "json",
			success: function(data){
				if (data.code == 0){
					ipt.remove();
					operationBtn.attr('nowType',0).attr('title','编辑').removeClass('signDescSave').addClass('signEdit');
					$('.custom-sign-myj span.module[uid="'+moduleName+'"]').attr('data-content',iptVal);
					$('.selCustomTagsBox a.signCont[uid="' + moduleName + '"] .signContent').text(iptVal);//更新下批量编辑里面的内容
				}
			}
		});
	};
	// 下拉remove
	var customSignInit = function(){
		$('.custom-sign-myj .signDropdown').remove();
	};
	var isGreen = "";
	var isYellow = "";
	var isOrange = "";
	var isRed = "";
	var isViolet = "";
	var isBlue = "";
	var cornflowerBlue = "";
    var pink = "";
    var teal = "";
    var turquoise = "";
	var greenContent = "";
	var yellowContent = "";
	var orangeContent = "";
	var redContent = "";
	var violetContent = "";
	var blueContent = "";
	var cornflowerBlueContent = "";
    var pinkContent = "";
    var tealContent = "";
    var turquoiseContent = "";
	// 下拉确定
	var customSignEnter = function(obj){
		var customSign = $(obj).closest('.custom-sign-myj');
		var customOrderId = customSign.find('input.moduleOrderId').val();
		var num = 0;
		customSign.find('span.module').addClass('myj-hide');
		obj.find('a.signCont').each(function(){
			var dataType = $(this).data('type');
			var uid = $(this).data('name');
			var txt = $.trim($(this).find('span.signContent').text());
			$('.custom-sign-myj span.module[uid="'+uid+'"]').attr('data-content',txt);
			if(dataType == 1){
				var span = customSign.find('span.module[uid="'+uid+'"]');
				span.removeClass('myj-hide');
				num ++;
			}
			if (uid == "moduleA"){
				isGreen = dataType;
				greenContent = txt;
			}
			if (uid == "moduleB"){
				isYellow = dataType;
				yellowContent = txt;
			}
			if (uid == "moduleC"){
				isOrange = dataType;
				orangeContent = txt;
			}
			if (uid == "moduleD"){
				isRed = dataType;
				redContent = txt;
			}
			if (uid == "moduleE"){
				isViolet = dataType;
				violetContent = txt;
			}
			if (uid == "moduleF"){
				isBlue = dataType;
				blueContent = txt;
			}
            if (uid == "moduleW"){
                cornflowerBlue = dataType;
                cornflowerBlueContent = txt;
            }
            if (uid == "moduleX"){
                pink = dataType;
                pinkContent = txt;
            }
            if (uid == "moduleY"){
                teal = dataType;
                tealContent = txt;
            }
            if (uid == "moduleZ"){
                turquoise = dataType;
                turquoiseContent = txt;
            }
		});
		$.ajax({
			type: "POST",
			url: "/package/addOrUpdateUserComment.json",
			data: {"isGreen" : isGreen, "isYellow" : isYellow, "isOrange" : isOrange, "isRed" : isRed, "isViolet" : isViolet, "isBlue" : isBlue, "cornflowerBlue" : cornflowerBlue, "pink" : pink, "teal" : teal, "turquoise" : turquoise,
				"greenContent": greenContent, "yellowContent": yellowContent, "orangeContent": orangeContent, "redContent": redContent, "violetContent": violetContent, "blueContent": blueContent, "cornflowerBlueContent":cornflowerBlueContent, "pinkContent":pinkContent, "tealContent":tealContent,"turquoiseContent":turquoiseContent,
				"orderId" : customOrderId, history: $('#keepState').data('history') === 'all' ? 'history' : ''},
			dataType: "json",
			success: function(data){
				if (!+data.code){
					if (!num) customSign.find('span.module-default').removeClass('myj-hide');
					customSignInit();
				} else {
					$.fn.message({type: 'error', msg: '自定义标记失败'});
				}
			}
		});
	};

	var contentType = "";
	// 下拉框里操作按钮点击
	$(doc).off('click','.signDropdown a[uid="operation"]');
	$(doc).on('click','.signDropdown a[uid="operation"]',function(){
		var type = $(this).attr('nowType');
		var signCont = $(this).closest('li').find('.signCont');
		var moduleName = signCont.attr('uid');
		var txtObj = signCont.find('.signContent');
		if(type == 0){
			var inputObj = $('<input type="text" maxlength="99"/>');
			inputObj.val(txtObj.text());
			signCont.append(inputObj);
			signCont.find('input[type="text"]').focus().select();
			//$(this).attr('nowType',1).removeClass('glyphicon-pencil').addClass('glyphicon-floppy-disk');
			$(this).attr('nowType',1).attr('title','保存').removeClass('signEdit').addClass('signDescSave');
		}else{
			var ipt = signCont.find('input[type="text"]');
			var obj = $(this).closest('.signDropdown');
			signIptEnter(obj, moduleName, ipt);
		}
	});
	// 下拉框里input回车事件
	$(doc).off('keypress','.signDropdown input[type="text"]');
	$(doc).on('keypress','.signDropdown input[type="text"]',function(e){
		var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
		if (keyCode == 13) {
			var moduleName = $(this).closest('.signCont').attr('uid');
			var obj = $(this).closest('.signDropdown');
			var ipt = $(this);
			signIptEnter(obj,moduleName,ipt);
			return false;
		}
	});
	// 下拉框标记点击事件
	$(doc).on('click','.signDropdown a.signCont',function(){
		var type = $(this).data('type');
		var signState = $(this).find('span.signState');
		if(type == 0){
			signState.removeClass('myj-hide');
			$(this).data('type',1);
		}else{
			signState.addClass('myj-hide');
			$(this).data('type',0);
		}
	});
	// 防冒泡
	$(doc).on('click','.signDropdown a.signCont input[type="text"]',function(event){
		event.stopPropagation();
	});
	//标记模块下的单个标记点击
	$(doc).off('click','.custom-sign-myj span.module');
	$(doc).on('click','.custom-sign-myj span.module',function(){
		/*2017.1.20 byzym 自定义标记修改点击*/
		var signDroDow=$(this).closest(".custom-sign-myj").find(".signDropdown");
		if(signDroDow.length>0) {
			signDroDow.remove();
			return;
		}
		customSignInit();
		var customSign = $(this).closest('.custom-sign-myj');
		var selHtmlObj = $(selHtml);
		var ul = selHtmlObj.find('ul');
		customSign.find('.module').each(function(){
			var uid = $(this).attr('uid');
			if(uid != 'default'){
				var li = $(selLiHtml);
				var signCont = li.find('a.signCont');
				signCont.addClass(uid);
				signCont.attr('uid', uid);
				signCont.data('name',uid);
				var txt = $(this).attr('data-content');
				if(txt){
					signCont.find('span.signContent').text(txt).attr('title', txt);
				}
				if($(this).hasClass('myj-hide')){
					signCont.data('type',0);
				}else{
					signCont.data('type',1);
					signCont.find('span.signState').removeClass('myj-hide');
				}
				ul.append(li);
			}
		});
		customSign.append(selHtmlObj);
	});
	// 鼠标点击位置如果不是下拉层，下拉hide;
	$(doc).click(function (e) {
		if(!e){
			var e = window.event;
		}
		//获取事件点击元素
		var targ = e.target;
		//获取元素名称
		//var tname = targ.tagName;
		var uid = $(targ).closest('.custom-sign-myj').attr('uid');
		if(uid != 'custom-sign-myj'){
			customSignInit();
		}
	});
	// 下拉btn动作
	$(doc).off('click','.signDropdown .btnGroup .button');
	$(doc).on('click','.signDropdown .btnGroup .button',function(){
		var uid = $(this).attr('uid');
		if(uid == 'cancel'){
			var obj = $(this).closest('.signDropdown');
			customSignInit();
		}else if(uid == 'enter'){
			var obj = $(this).closest('.signDropdown');
			customSignEnter(obj);
		}
	});
	// 搜索用标签点击
	$(doc).off('click','.custom-sign-sel span.module');
	$(doc).on('click','.custom-sign-sel span.module',function(){
        commonSearchSave.removeSearchModalActiveClass();//去掉常用搜索模板的选中样式
		var type = $(this).data('type');
		if(type == 0){
			$(this).data('type',1);
			$(this).append(selSignHtml);
		}else{
			$(this).data('type',0);
			$(this).empty();
		}
		updatePickingInstructionsData();//点击的时候实时更新下拣货说明的参数
	});

	//订单批量自定义事件处理
	$(doc).off('mouseover','.selCustomTagsBtn');
    $(doc).on('mouseover','.selCustomTagsBtn',function(){
    	var $signCont = $(this).closest('.selCustomTagsBox').find('.signCont');
        $signCont.data('type', 0);
        $signCont.find('.signState').addClass('myj-hide');
	});

    //订单详情弹窗里禁止用户勾选含电和含非液体化妆品
    $(doc).off('click','input.smtCustomCheck:checked').on('click','input.smtCustomCheck:checked', function(){
        $('#disableSetTip').modal('show');
        $(this).prop('checked', false);
        var $disableSetTipCloseBtn = $('.disableSetTipCloseBtn'), //速卖通报关含电提示说明弹层的关闭按钮
            countNum = 3, //倒计时
            clearSetInterval = null;

        $disableSetTipCloseBtn.prop('disabled', true).html('(3s)关闭'); //先把关闭按钮禁用
        var clearSetInterval = setInterval(function () { //加个定时器
            countNum--;
            $disableSetTipCloseBtn.prop('disabled', true).html('(' + countNum + 's)关闭');
            if(!+countNum){ //当倒计时三秒后，关闭按钮解除禁用
                clearInterval(clearSetInterval);
                clearSetInterval = null;
                $disableSetTipCloseBtn.prop('disabled', false).html('关闭');
            }
        }, 1000);
    });

})(jQuery,document);

/*加密一件代发*/
var queryShippingToPfhoo = function (puid, orderId, spu) {
	var url = "http://www.pfhoo.com/dmxCheckOrder?key=4E9AA1513CCA415AA16E157F7E9BD15A&userId="+encode64(puid)+"&orderId="+encode64(orderId)+"&spuId="+spu;
	var wo = window.open('about:blank', '_blank');
	wo.location.href = url;
};

/**标记/去除优先发货**/
var signPriorOrBanShip = function(packageId,type,val){ // type: 0 优先发货操作 1 禁止发货操作
	var isMatchSKU = false;
	$("input[name='relationProductId']").each(function () {
		var proId = $(this).val();
		if(proId != "" && proId != undefined){
			isMatchSKU = true;
			return false;
		}
	});
	if(type == '1' && val == '2'){ //同步时自动标记的禁止发货
		$.fn.message({type: "error", msg: "订单已退款或取消（买家申请取消），不能取消禁止处理标记"});
		return false;
	}
	if(!isMatchSKU && type == '0'){
		$.fn.message({type: "error", msg: "未配对商品SKU，不能标记优先分配库存"});
		return false;
	}
	if(packageId == "" || packageId == undefined){
		$.fn.message({type: "error", msg: "标记操作失败"});
		return;
	}else{
		var signedPrior = $("#signPriorValue").val();
		var signedBan = $("#signBanValue").val();
		if(signedPrior == 'true' && type == '1'){ //已标记优先发货再标记禁止发货
			$.fn.message({type: "error", msg: "请先取消优先分配库存标记，再重新尝试"});
			return;
		}else if((signedBan == '1' || signedBan == '2' || signedBan == '4' || signedBan == '7') && type == '0'){ //已标记禁止发货再标记优先发货
			$.fn.message({type: "error", msg: "请先取消禁止处理标记，再重新尝试"});
			return;
		}
		$.ajax({
			type: "POST",
			url:"order/orderPriorOrBanShip.json",
			data:  {"packageId":packageId,"type":type},
			dataType: "json",
			success: function (data) {
				if(data.code == 0){
					$.fn.message({type: "success", msg: data.msg});
					if(type == 0){ //优先发货操作
						if(signedPrior == 'true'){
							$("#signPriorValue").val('false');
							$("a[name='signPrior']").html("优先分配库存");
						}else{
							$("#signPriorValue").val('true');
							$("a[name='signPrior']").html("取消优先分配库存");
						}
					}else if(type == '1'){ //禁止发货操作
						if(signedBan == '1' || signedBan == '4' || signedBan == '7' || signedBan == '8'){
							$("#signBanValue").val('0');
							$("a[name='signBan']").html("禁止处理");
						}else{
							$("#signBanValue").val('1');
							$("a[name='signBan']").html("取消禁止处理");
						}
					}
				}else if(data.code == -1){
					$.fn.message({type: "error", msg: data.msg});
				}
			}
		});
	}
}
/**更新速卖通禁止发货处理状态**/
var updateSmtShipSignBan = function (dxmOrderId) {
	if (dxmOrderId == "" || dxmOrderId == undefined) {
		$.fn.message({type: "error", msg: "处理的订单有误，请刷新重试"});
		return;
	} else {
		$.ajax({
			type: "POST",
			url: "order/updateSmtShipSignBan.json",
			data: {"dxmOrderId": dxmOrderId},
			dataType: "json",
			success: function (data) {
				if (data.code == 0) {
					$.fn.message({type: "success", msg: data.msg});
					refreshAjaxPage('package');
				} else {
					$.fn.message({type: "error", msg: data.msg});
				}
			}
		});
	}
}

/********************************** 订单详情增加商品 **********************************/
/*控制详情页编辑*/
var editShippingInformation = function(val){
	var mBody = $("#packageDetailModal").find('.modal-body');
	var mFooter = $("#packageDetailModal").find('.modal-footer');
	mBody.find('.orderList').addClass('myj-hide');
	if(val == 1){
		mBody.find('.editOrderInfoList').removeClass('myj-hide');
		mFooter.find('.modifyBtn').removeClass('myj-hide');
		var packageId = $("#detailPackageId").val();
		$.ajax({
			type: "POST",
			url: 'package/showAddProduct.htm',
			data: {"packageId" : packageId},
			dataType: "html",
			success: function(data){
				$('#loading').modal('hide');
				$('#editOrderProductInfo').html(data).find('[data-toggle="popover"]').popover();
			}
		});
		$("#addProductRecoveryBtn").css("display", "none");
	}else{
		mBody.find('.orderInfoList').removeClass('myj-hide');
		$("#addProductRecoveryBtn").css("display", "");
	}
};

/** 移除新增商品 **/
var removeAddProduct = function(obj){
	var pid = $(obj).parent().attr("data-id");
	var trObj = $(obj).closest("table.tableIn").closest('tr');
	if(pid > 0){
		$(trObj).find("input").val(0);
		$(trObj).css("display","none");
	} else {
		$(trObj).remove();
	}
};

/*还原提示框*/
var recoveryProductConfirm = function(){
	$('#restoreConfirmationLayer .modal-dialog').css('width','500px');
	$('#restoreConfirmationLayer').modal('show');
};

/** 执行还原操作 **/
var executeRecoveryOldProduct = function(){
	var packageId = $("#detailPackageId").val();
	$.ajax({
		type: "POST",
		url: 'package/recoveryProduct.json',
		data: {"packageId" : packageId},
		dataType: "json",
		success: function(data){
			if(data.code == 0){
				$.fn.message({type:"success", msg:"还原成功！"});
				$('#restoreConfirmationLayer').modal('hide');
				dxmPackageDetail(packageId);
			} else {
				$.fn.message({type:"error", msg: data.msg});
			}
		}
	});
};

/** 增加产品数据 **/
var addOrderProduct = function(pid, obj, isAddGift){
	var $table = $('#dxmOrderAddProductTable'),
		productList = $table.find(".addProduct");	// 检测是否有重复的产品

	for(var i=0; i< productList.length; i++) {
		var prObj = productList[i];
		var dataPid = $(prObj).attr("data-pid");
		var isAdd = $(prObj).attr("data-add");
		if(pid == dataPid && isAdd == 1){
			$.fn.message({type:"error", msg: "当前商品已存在，请选择其他商品！"});
			return;
		}
	}
	var productImg = $(obj).parent().attr("data-img");
	var sku = $(obj).parent().attr("data-sku");
	var name = $(obj).parent().attr("data-name");
	// isAddGift  1：选择来自追加礼品   2：选择来自追加商品
	var str = getOrderProductStr(0, pid, sku, name, productImg, '', 1, -1, isAddGift);
	$table.append(str);
	//如果data-add是0，表示原有输入框就是禁用状态，重置后继续禁用，后面追加的不做禁用
    var $oldDisabledTr = $table.find('tr.addProduct[data-add="0"]');
    if ($oldDisabledTr.length) $oldDisabledTr.find('.rightInput input').prop('disabled', true);
	closeInIdentifyNoQuoteModal();
};

/** 执行增加产品 **/
var isExecuteAddProduct = false;
var executeAddProduct = function(){
    if(isExecuteAddProduct){
        $.fn.message({type:"error", msg: "正在执行追加商品！"});
        return;
    }
    isExecuteAddProduct = true;
	var packageId = $("#detailPackageId").val();
	var productList = $("#dxmOrderAddProductTable").find(".addProduct");	// 参数格式：是否新增±数量±仓库商品ID±主键ID±礼品(1)还是商品(2)

	var param = '';
	var deleteCount = 0;
	for(var i=0; i< productList.length; i++){
		var obj = productList[i];
		var id = $(obj).attr("data-id");
		var pid = $(obj).attr("data-pid");
		var isAddGift = $(obj).attr("data-isAddGift");		// 礼品(1)还是商品(2)
		var count = $(obj).find("input").val();
		count = $.trim(count);
		if(isNaN(count) || count == '' || count < 0){
			$.fn.message({type: 'error', msg: '数量请输入大于0的整数'});
			$(obj).find("input").focus();
			isExecuteAddProduct = false;
			return;
		}
		if (count == 0){
            deleteCount ++;
		}
		if(param == ''){
			param = $(obj).attr("data-add") + "±" + count + "±" +pid+ "±" + id + "±" + isAddGift;
		} else {
			param += ";" + $(obj).attr("data-add") + "±" + count + "±" +pid+ "±" + id + "±" + isAddGift;
		}
	}
	var paramCount = param && param.split(";").length;

	if(param == '' || deleteCount == paramCount){
		$.fn.message({type:"error", msg: "请至少保留一个商品！"});
		isExecuteAddProduct = false;
		return;
	}
    $('#loading').modal('show');
	$.ajax({
		type: "POST",
		url: 'package/addProduct.json',
		data: {"packageId" : packageId, "param" : param, "addFromOrderDetail" : 1},
		dataType: "json",
		success: function(data){
            $('#loading').modal('hide');
            isExecuteAddProduct = false;
			if(!+data.code){
				$.fn.message({type:"success", msg:"商品保存成功！"});
				dxmPackageDetail(packageId, undefined, 0, 1);
			} else {
				$.fn.message({type:"error", msg: data.msg});
			}
		},
        error: function () {
            $('#loading').modal('hide');
            isExecuteAddProduct = false;
        }
	});
};

/** 编辑时还原新增产品 **/
var editRecoveryAddProduct = function(){
	var $table = $('#dxmOrderAddProductTable');

	$table.find('tbody').html('');
	$("#addProductStorageTable").find(".productInfo").each(function(){
		var id = $(this).attr("data-id");
		var pid = $(this).attr("data-pid");
		var sku = $(this).attr("data-sku");
		var name = $(this).attr("data-name");
		var productImg = $(this).attr("data-img");
		var count = $(this).attr("data-count");
		var isAdd = $(this).attr("data-add");
		var stockNum = $(this).attr("data-stocknum");
		var isAddGift = $(this).attr("data-isaddgift");
		var str = getOrderProductStr(id, pid, sku, name, productImg, count, isAdd, stockNum, isAddGift);
		$table.append(str);
	});
	//如果data-add是0，表示原有输入框就是禁用状态，重置后继续禁用，后面追加的不做禁用
    var $oldDisabledTr = $table.find('tr.addProduct[data-add="0"]');
    if ($oldDisabledTr.length) $oldDisabledTr.find('.rightInput input').prop('disabled', true);
};

/** 获取新增发货商品str **/
var getOrderProductStr = function(id, pid, sku, name, productImg, count, isAdd, stockNum, isAddGift){
	if(stockNum == undefined){
		stockNum = 0;
	}
	var stockStr = '';
	if(pid > 0 && stockNum >= 0){
		if(stockNum == 0){
			stockStr = '<p class="m0 garyText">「可用库存：<span class="fW600 fRed">'+ stockNum +'</span>」</p>';
		} else {
			stockStr = '<p class="m0 garyText">「可用库存：<span class="fW600 fGreen">'+ stockNum +'</span>」</p>';
		}
	}
	var str = '<tr class="addProduct" data-id="'+id+'" data-pid="'+pid+'" data-count="'+count+'" data-add="'+ isAdd +'" data-isAddGift="'+ isAddGift +'" data-stocknum="'+ stockNum +'">'+
		'<td class="productInfo">'+
		'<table class="tableIn">'+
		'<tr>'+
		'<td>'+
		'<div class="listImgOut">'+
		'<div class="listImgIn"><img class="imgCss" src="'+productImg+'"/></div>'+
		'</div>'+
		'</td>'+
		'<td>'+
		'<div class="pull-left leftCon">'+
		'<p class="m0">' + strEscapeCharacter(sku) + 'x '+ count +'</p>'+
		'<p class="m0 garyText">'+ strEscapeCharacter(name) +'</p>'+ stockStr +
		'</div>'+
		'<div class="pull-right rightInput"><input type="text" class="form-control" value="'+ count +'" placeholder="填写数量" oninput="clearMistakeNumber(this);" />'+
		'<div class="operating mTop10" data-id="'+ id +'" data-pid="'+ pid +'"><a href="javascript:" onclick="removeAddProduct(this);">移除</a></div></div>'+
		'</td>'+
		'</tr>'+
		'</table>'+
		'</td>'+
		'</tr>';
	return str;
};

/* 1000单动作 条件参数获取 */
var getOneThousandParaData = function (isFlag) {
	var shopId = $("#keepState").data("shopid");
	if (shopId == undefined || shopId == '') {
		shopId = "-1";
	}
	// 已经兼容多个搜索
	var authid = $("#keepState").data("authid");
	if (authid == undefined || authid == '') {
		authid = "-1";
	}
	var platform = $("#keepState").data("platform");
	if (platform == undefined) {
		platform = "";
	}
	var state = $("#keepState").data("state");
	if (state == undefined) {
		state = "paid";
	}
	var country = $("#keepState").data("country");
	if (country == undefined || country == '') {
		country = "";
	}
	var startTime = "";
	var endTime = "";
	if (state == 'shipped') {
		startTime = $("#keepState").data("starttime");
		endTime = $("#keepState").data("endtime");
	}
	var isSearch = $("#keepState").data("search");
	if (isSearch == undefined || isSearch == '') {
		isSearch = "0";
	}
	var isVoided = $("#keepState").data("isvoided");
	if (isVoided == undefined) {
		isVoided = "0";
	}
	var isRemoved = $("#keepState").data("isremoved");
	if (isRemoved == undefined) {
		isRemoved = "0";
	}
	var ruleId = $("#keepState").data("ruleid");
	if (ruleId == undefined) {
		ruleId = "-1";
	}
	var orderField = $("#keepState").data("orderfiled");
	if (orderField == undefined) {
		orderField = "";
	}
	var storageId = $("#keepState").data("storageid");
	if (storageId == undefined || storageId == "") {
		storageId = 0;
	}
	var isOversea = $("#keepState").data("isoversea");
	var sysrule = $("#keepState").data("sysrule");
	if (sysrule == undefined) {
		sysrule = "";
	}
	var applyType = $("#keepState").data("applytype");
	if (applyType == undefined) {
		applyType = "";
	}
	var applyStatus = $("#keepState").data("applystatus");
	if (applyStatus == undefined) {
		applyStatus = "";
	}
	var printJh = $("#keepState").data("printjh");
	if (printJh == undefined) {
		printJh = "-1";
	}
	var printMd = $("#keepState").data("printmd");
	if (printMd == undefined) {
		printMd = "-1";
	}
	var commitPlatform = $("#keepState").data("commitplatform");
	if (commitPlatform == undefined) {
		commitPlatform = "";
	}
	var fieldType = $("input[name='fieldType']:checked").val();
	if (fieldType == '' || fieldType == undefined) {
		fieldType = 1;
	}
	var productStatus = $("#keepState").data("productstatus");
	var jhComment = $("#keepState").data("jhcomment");
	var isFree = $("#keepState").data("isfree");
	var isBatch = $("#keepState").data("isbatch");
	var custom = $("#keepState").data("custom");
	var timeOut = $("#timeOutHidden").val();

	// 返回参数对象
	var paraData = {
		"oneThousandActionFlag": 1,
		"shopId": shopId,
		"authId": authid,
		"platform": platform,
		"state": state,
		"country": country,
		"startTime": startTime,
		"endTime": endTime,
		"isSearch": isSearch,
		"isVoided": isVoided,
		"isRemoved": isRemoved,
		"ruleId": ruleId,
		"orderField": orderField,
		"storageId": storageId,
		"isOversea": isOversea,
		"sysRule": sysrule,
		"applyType": applyType,
		"applyStatus": applyStatus,
		"printJh": printJh,
		"printMd": printMd,
		"commitPlatform": commitPlatform,
		"productStatus": productStatus,
		"jhComment": jhComment,
		"isFree": isFree,
		"isBatch": isBatch,
		"custom": custom,
		"timeOut": timeOut,
		"fieldType": fieldType
	},
	$shopGroupId = $('#shopGroupId'),
	shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

	if (isFlag && !$('.initialize').hasClass('myj-hide')) {
		delete paraData.oneThousandActionFlag;
		paraData.packageIds = getCheckBoxValByName('packageId');
	}
	if (shopGroupId) paraData.shopGroupId = shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
	return paraData;
};

var redirectUrl = function (obj) {
	var sourceUrl = $(obj).attr('data-url');
	if (sourceUrl) {
		if (sourceUrl.indexOf('detail.1688.com') !== -1 ||
		sourceUrl.indexOf('item.taobao.com') !== -1 ||
		sourceUrl.indexOf('detail.tmall.com') !== -1) {
			sourceUrl = encodeURIComponent($.trim(sourceUrl));
			var wo = window.open('about:blank', '_blank');
			wo.location.href = '/productSource/redirectUrl.json?module=order&sourceUrl='+sourceUrl;
		} else {
			window.open(sourceUrl, '_blank', 'noopener,noreferrer');
		}
	}
};
var fillCheckeBoxValue = function (obj) {
    $(obj).prop('checked') ? $(obj).val(1) :$(obj).val(0);
};
// 为了传值方便将选中的结果赋给另外一个值
var fillCheckedValueToOther = function (obj) {
    fillCheckeBoxValue(obj);
    $(obj).prop('checked') ? $(obj).next().val(1) : $(obj).next().val(0);
};

//小秘云仓列表批量操作控制
var orderYuncangListBtnInit = function(){
    var type = $('.orderListNav').children('ul').children('li.active').data('type'),
        $btn = $('#ceilDropdownMenu7, #dropdownMenu7').closest('.dropdown');

	$btn.find('li[data-status]').addClass('hide');
	switch (type) {
		case 'success':
            $btn.removeClass('hide');
		    var $ulBtnActive = $('.ulBtnBox').find('li.liFoucs'),
                cType = $ulBtnActive.data('type');

            if($ulBtnActive.length === 1 && cType === 'success_cancel'){
                $btn.find('li[data-status="1"]').removeClass('hide');
            }else{
                $btn.find('li[data-status="1"]').removeClass('hide');
                $btn.find('li[data-status="3"]').removeClass('hide');
                $btn.find('li[data-status="5"]').removeClass('hide');
            }
			break;
        case 'fail':
            $btn.removeClass('hide');
            $btn.find('li[data-status="1"]').removeClass('hide');
            $btn.find('li[data-status="2"]').removeClass('hide');
            $btn.find('li[data-status="4"]').removeClass('hide');
            $btn.find('li[data-status="6"]').removeClass('hide');

            var applyStatus = $('#keepState').data('applystatus');

			if (applyStatus === 'commit_fail') {
				$btn.find('li[data-status="5"]').removeClass('hide');
			} else if (applyStatus === 'fail'){//只有运单号申请失败才显示
				$btn.find('li[data-status="8"],li[data-status="9"]').removeClass('hide');
			}
            break;
        case 'pending':
            $btn.addClass('hide');
            break;
		case 'commit_back':
			$btn.removeClass('hide');
			$btn.find('li[data-status="1"]').removeClass('hide');
			$btn.find('li[data-status="2"]').addClass('hide');
			$btn.find('li[data-status="4"]').removeClass('hide');
			$btn.find('li[data-status="6"]').removeClass('hide');
			$btn.find('li[data-status="7"]').removeClass('hide');
			$("#applyFailDiv2").css("display","none");
			break;
	}
};

/*小秘云仓--缺货中订单--查看商品占用库存数*/
var lookOccupyStockNum = function (obj, type) {
	var $loading = $('#loading'),
		$lookOccupyStockModal = $('#lookOccupyStockModal'),
		$obj = $(obj),
		id = $obj.attr('data-packid'),
		packName = $obj.attr('data-packname'),
		strHtml = '';
	// 初始化
	$lookOccupyStockModal.attr('data-type', type === undefined ? 0 : 1).find('.lookOccupyActiveBoxList1, .lockCount').removeClass('hide');
	$lookOccupyStockModal.find('.lookOccupyActiveBoxList2, .lookOccupyInfo').addClass('hide');

	$loading.modal('show');
	$.ajax({
		type: 'GET',
		url: gitWinLocHref() + 'package/getOrderLockInfo.json',
		data: {id: id},
		dataType: 'JSON',
		success: function(data){
			$loading.modal('hide');
			if(!+data.code) {
				var datas = data.data || {},
					packageState = datas.packageState,
					proInfo = datas.productList,
					warehouseName = datas.warehouseName;
				if(proInfo && proInfo.length) {
					$lookOccupyStockModal.modal('hide');
					var $keepState = $('#keepState'),
						orderIds = $keepState.data('orderIds'),//订单id数组
						lookOccupyNum = $keepState.data('lookOccupyNum') || -1,//当前订单的id在数组中的位置
						currPage= $('#pageNo').val() || 1,//当前页
						totalPage= $('#totalPage').val() || 30;//总页数

					lookOccupyNum = parseInt(lookOccupyNum);
					currPage = parseInt(currPage);
					totalPage = parseInt(totalPage);

					if(orderIds!=null) {
						// 初始化
						$lookOccupyStockModal.find('.upOrDownDiv').removeClass('hide');
						$lookOccupyStockModal.find('.upbtnForOrder').attr('onclick', 'upOrDownLookOccupy(\'up\');').removeClass('btn-disabled');
						$lookOccupyStockModal.find('.downbtnForOrder').attr('onclick', 'upOrDownLookOccupy(\'down\');').removeClass('btn-disabled');
						$lookOccupyStockModal.find('.upShow').attr('data-original-title', '');
						$lookOccupyStockModal.find('.downShow').attr('data-original-title', '');

						if(orderIds.length === 1){//当前页只有一条
							$lookOccupyStockModal.find('.upbtnForOrder').attr('onclick', '');
							$lookOccupyStockModal.find('.downbtnForOrder').attr('onclick', '');
							$lookOccupyStockModal.find('.upOrDownDiv').addClass('hide');
						}else if (+lookOccupyNum === -1) {
							lookOccupyNum = orderIds.indexOf(id);
							$keepState.data('lookOccupyNum', lookOccupyNum);
						}
						if(+currPage === 1 && +lookOccupyNum === 0){//第一页第一条
							$lookOccupyStockModal.find('.upbtnForOrder').attr('onclick', '').addClass('btn-disabled');
							$lookOccupyStockModal.find('.upShow').attr('data-original-title', '已经是第一个了');
						}else if(+currPage === +totalPage && +lookOccupyNum === (orderIds.length - 1)){//最后一页最后一条
							$lookOccupyStockModal.find('.downbtnForOrder').attr('onclick', '').addClass('btn-disabled');
							$lookOccupyStockModal.find('.downShow').attr('data-original-title', '已经是最后一个了');
						}
					}
					$lookOccupyStockModal.attr('data-packid', id);
					//渲染发货仓库内容
					$('#sendGoodsWarehouse').text("发货仓库：".concat(warehouseName));
					//获取要渲染弹层里的表格内容
					$.each(proInfo, function (i, j) {
						strHtml += renderOccupyStockHtml(j, 'default');
					});
					// 注册提示文本
					$('[data-toggle="popover"]').popover({
						trigger: 'hover'
					});
					//注册图片放大
					$('div.imgDivIn').picZoom({
						imgWidth: '296',
						imgHeight: '296',
						divWidth: '300',
						divHeight: '300'
					}, 500);
				}
				//渲染弹层里的表格内容
				$('#occupyStockTable > tbody').html(strHtml);
				//占用详情弹框包裹号
				$('#packName').text(packName);
				$('.hasLockNum').removeClass('hide');
				$lookOccupyStockModal.modal('show');
				if(packageState === 'to_lock' || packageState === 'to_generate'){
					$('#ycAddBtn').css("display", "");
				} else {
					$('#ycAddBtn').css("display", "none");
				}
			} else {
				showNetError();
			}
		},
		error: function() {
			$loading.modal('hide');
			showNetError();
		}
	});
};
//跳转到上一个或下一个订单详情页
var upOrDownLookOccupy=function (type) {
	var orderIds = $("#keepState").data("orderIds"),//订单id数组
		lookOccupyNum = $("#keepState").data("lookOccupyNum"),//当前订单的id在数组中的位置
		currPage= $('#pageNo').val() || 1,//当前页
		totalPage= $('#totalPage').val() || 30;//总页数

	lookOccupyNum = parseInt(lookOccupyNum);
	currPage = parseInt(currPage);
	totalPage = parseInt(totalPage);

	if(orderIds != null){
		if(type == "up"){//跳转到上一个订单详情页
			if(lookOccupyNum == 0 && currPage > 1){//非第一页第一条
				var pageNo = parseInt(currPage) - 1;
				jumpForOrderNum(pageNo, 'up', 'lookOccupyNum');
			} else{
				$("#keepState").data("lookOccupyNum", lookOccupyNum - 1);
				lookOccupyStockNum($('a[data-packid="' + orderIds[lookOccupyNum - 1] + '"]'));
			}
		}else if(type == "down"){//跳转到下一个订单详情页
			if(lookOccupyNum == orderIds.length-1 && currPage < totalPage){//非最后一页最后一条
				var pageNo = currPage + 1;
				jumpForOrderNum(pageNo, 'down', 'lookOccupyNum');
			}else{
				$("#keepState").data("lookOccupyNum", lookOccupyNum + 1);
				lookOccupyStockNum($('a[data-packid="' + orderIds[lookOccupyNum + 1 ] + '"]'));
			}
		}
	}
};
// 订单详情操作入口
var lookOccupyActiveFn = function (type) {
	var $lookOccupyStockModal = $('#lookOccupyStockModal'),
		$wareHoseProductsQuoteModal = $('#wareHoseProductsQuoteModal'),
		packid = $lookOccupyStockModal.attr('data-packid'),
		$upOrDownDiv = $lookOccupyStockModal.find('.upOrDownDiv'),
		$occupyStockTableTrs = $lookOccupyStockModal.find('tbody > tr'),
		$lookOccupyActiveBoxList1 = $lookOccupyStockModal.find('.lookOccupyActiveBoxList1'),
		$lookOccupyActiveBoxList2 = $lookOccupyStockModal.find('.lookOccupyActiveBoxList2'),
		$loading = $('#loading');

	switch (type) {
		case 'change':
			lookOccupyStockInitValidForm(); //订单小秘云仓点击查看占用弹层的编辑追加按钮，调用注册表单验证插件事件
			$lookOccupyActiveBoxList1.addClass('hide');
			$lookOccupyActiveBoxList2.removeClass('hide');
			$upOrDownDiv.addClass('hide');
			$lookOccupyStockModal.find('.lockCount').addClass('hide');
			$lookOccupyStockModal.find('.lookOccupyInfo').removeClass('hide');
			//放开输入框并初始化
			$occupyStockTableTrs.each(function() {
				var $this = $(this),
					$b = $this.find('.orderNum b'),
					$input = $this.find('.orderNum input');

				$b.addClass('hide');
				$this.find('.orderNum span,td.infos').addClass('hide');
				$('.hasLockNum').addClass('hide');
				$input.removeClass('hide').val($b.text());
			});
			break;
		case 'add':
			var $selectWareHoseProductsPageList = $('#selectWareHoseProductsPageList');
			// 初始化
			placementInfoElasticLayer('', $wareHoseProductsQuoteModal, 'lookOccupy'); //弹层放置产品信息
			$selectWareHoseProductsPageList.html('');
			$loading.modal('show');
			$.ajax({
				type: 'POST',
				url: gitWinLocHref() + 'yuncangWarehouseSku/warehouseSkuList.htm',
				data: {},
				dataType: 'html',
				success: function(data){
					$loading.modal('hide');
					var $selectProposalBatchPageList = $('#selectProposalBatchPageList'); //清空批量弹层数据
					$selectProposalBatchPageList.empty();
					$selectWareHoseProductsPageList.empty();
					$selectWareHoseProductsPageList.html(data);
					$wareHoseProductsQuoteModal.customModal('show');
				},
				error: function () {
					$loading.modal('hide');
				}
			});
			break;
		case 'quit':
			lookOccupyStockNum($('a[data-packid="' + packid + '"]'));
			break;
	}
};

/** 增加小秘云仓 **/
var addYcOrderProductFlag = false;
var addYcOrderProduct = function(packId){
	var $goodsList = $('#occupyStockTBody').find('.orderNum'),
		flag = true,
		vo = {
			productList: [],
			dxmOrderId: packId
		},
		$loading = $('#loading');

	$goodsList.each(function() {
		var $this = $(this),
			option = {
				goodsId: $this.attr('data-goodsid'),
				goodsCount: $this.find('input').val(),
				originCount: $this.find('b').text()
			};
		if(flag && option.goodsCount > 0) flag = false;
		vo.productList.push(option);
	});
	if(flag){
		$.fn.message({type:"error", msg: "最少保留一个商品！"});
		return;
	}
	if(addYcOrderProductFlag){
		$.fn.message({type:"error", msg: "正在执行追加商品！"});
		return;
	}
	addYcOrderProductFlag = true;
	$loading.modal('show');
	$.ajax({
		type: "POST",
		url: gitWinLocHref() + 'package/addYcProduct.json',
		data: JSON.stringify(vo),
		dataType: 'json',
		contentType: 'application/json',
		success: function(data){
			addYcOrderProductFlag = false;
			$loading.modal('hide');
			if(data.code == 0){
				$.fn.message({type:'success', msg: '更新云仓商品成功'});
				lookOccupyStockNum($('a[data-packid="' + packId + '"]'));
			} else {
				$.fn.message({type:'error', msg: data.msg});
			}
		},
		error: function () {
			addYcOrderProductFlag = false;
			$loading.modal('hide');
		}
	});
};

// 渲染单个tr的方法
var renderOccupyStockHtml = function (obj, type) {
	var trStr = '<tr class="content">' +
		'<td class="imgDivOutTd">' +
		'<div class="imgDivOut m-right0">' +
		'<div class="imgDivIn epz_out">' +
		'<img class="img-css imgCss lazy" src="&{imgUrl}">' +
		'</div></div>' +
		'</td>' +
		'<td class="imgDivTitleTd p-left5">' +
		'<div><span class="f-blue pointer limingcentUrlpic">&{sku}</span></div>' +
		'<div class="gray-c no-new-line2" title="&{name}"><span>&{name}</span></div>' +
		'</td>' +
		'<td class="w100 f-center orderNum" data-goodsid="&{goodsId}"><b class="&{showB}">&{orderNum}</b><span class="&{showB}">/</span><span class="&{lockClass} &{showB}">&{lockCount}</span><input class="form-control Validform_error &{showInput}" type="text" datatype="*,less100000" oninput="value=value.replace(/[^0-9]/g,\'\');value=value < 100000 ? value : 100000;"></td>' +
		'<td class="p-right10 w100 f-right &{showB} infos">\n' +
		'     <div>可用：&{availableNum}</div>\n' +
		'     <div>预售：&{lockStockNum}</div>\n' +
		'     <div>在途：&{onPassageNum}</div>\n' +
		'     <div>总量：&{stockNum}</div>\n' +
		'</td>' +
		'</tr>';

	return trStr.format({
		imgUrl: obj.imgUrl || '/static/img/kong.png',
		name: obj.name || '',
		sku: obj.sku || '',
		goodsId : obj.goodsId || 0,
		orderNum: obj.orderNum || 0,
		lockCount: obj.lockCount || 0,
		lockClass: obj.lockCount < obj.orderNum ? 'f-red' : 'f-green',
		showB: type === 'default' ? '' : 'hide',
		showInput: type === 'add' ? '' : 'hide',
		availableNum: obj.availableNum || 0,
		lockStockNum: obj.lockStockNum || 0,
		onPassageNum: obj.onPassageNum || 0,
		stockNum: obj.stockNum || 0
	});
};


var lookOccupyStockInitValidForm = function () {
	// 小秘云仓列表批量操作控制-保存验证
	$('form.lookOccupyStock').Validform({
		btnSubmit: '.toSubmit',
		showAllError: true,
		tipSweep: false,
		ignoreHidden: false,//是否对隐藏表单验证
		datatype: {
			'less100000': function(objVal){
				if(objVal > 100000){
					return '最大100000';
				}
			}
		},
		tiptype: function(msg,o){
			//msg：提示信息;
			//o:{obj:*,type:*,curform:*}, obj指向的是当前验证的表单元素（或表单对象），type指示提示的状态，值为1、2、3、4， 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态, curform为当前form对象;
			//cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
			if(!o.obj.is('form')){//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
				var td = o.obj.closest('td');
				td.find('.errorMsg').remove();
				if(+o.type === 3) td.append('<div class="f-red f12 errorMsg mTop5" style="clear: both;"><span class="errorMsgContent">'+msg+'</span></div>');
			}
		},
		beforeSubmit:function(curform){
			//在验证成功后，表单提交前执行的函数，curform参数是当前表单对象。
			//这里明确return false的话表单将不会提交;
			var packid = curform.closest('#lookOccupyStockModal').attr('data-packid');
			addYcOrderProduct(packid);
			return false;
		}
	});
};


/*不打单发货参照物流映射改版的相关交互验证方法*/
var DELIVERY_WITHOUT_ORDER = (function ($, W, D) {
	var locHref = gitWinLocHref();

	//公用ajax请求方法
	var commonAjaxFn = function (url, ajaxData, dataType, successCall, errorCall, type, async) {
		var $loading = $('#loading');

		$loading.modal('show');
		$.ajax({
			type: type ? type : 'POST',
			url: locHref + url,
			data: ajaxData,
			dataType: dataType,
			async: !async,
			success: function(data){
				$loading.modal('hide');
				successCall && typeof successCall === 'function' && successCall(data);
			},
			error: function(){
				$loading.modal('hide');
				if(errorCall && typeof errorCall === 'function'){
					errorCall();
				}else {
					showNetError();
				}
			}
		});
	};

	//公用报错提示方法
	var commonMsgFn = function (msg, type, isText) {
		$.fn.message({type: type ? 'success' : 'error', msg: msg, isText: !!isText});
	};

	//清空节点公用方法
	var commonEmptyDomFn = function ($dom) {
		if($dom.length) $('<div></div>').append($dom).empty();
	};

	//速卖通选择带有other名称的承运商需要选择具体的实际承运商
	var showSmtBack = function($tr, code){
		var $smtBacks = $tr.find('.smtBack,.smtOtherSelBack'),
            $smtBack = $smtBacks.filter('.smtBack');

		if (!$.trim(code)) {
            $smtBacks.addClass('hide');
            $smtBack.removeClass('m-top5');
			return ;
		}

		if (!+code.indexOf('Other') || !+code.indexOf('OTHER')) {
            $smtBacks.removeClass('hide');
            $smtBack.addClass('m-top5');
		} else {
            $smtBacks.addClass('hide');
            $smtBack.removeClass('m-top5');
		}
	};

	//速卖通选择带有other名称的承运商需要选择具体的实际承运商
	var showOnBuyBack = function($tr, code){
		var $smtBacks = $tr.find('.onbuyBack');
		if (+code === 16) { //如果切换的value值是16，则需要显示填写追踪网址节点
            $smtBacks.removeClass('hide');
		} else {
            $smtBacks.addClass('hide');
		}
	};

	//初始化跟踪网址的弹层模板
	var initTrackModal = function () {
		var $setTrackWebsiteModal = $('#setTrackWebsiteModal'),
			$radioDefault = $('#choseSetType input[name="defaultSet"][data-type="0"]'),
			$radioOther = $('#choseSetType input[name="defaultSet"][data-type="1"]'),
			$defaultSetSel = $('#defaultSetSel'),// 指定运输商
			$shopifyBackUrl2 = $('#shopifyBackUrl2'),// 其他输入框
			$tr = $('#withOutPrintShippingDiv').find('tr[data-packid="' + $setTrackWebsiteModal.attr('data-packid') + '"]'),
			url = $.trim($tr.find('input[tag="backUrl"]').val());// 回显输入框

		if(url) {//有保存过
			if(url.indexOf('17track.net') !== -1) {//保存过含有17track.net的网址 勾选默认
				var historyCode = get17UrlParameter(url, 'fc');//获取url里的code参数值
				$radioDefault.click();
				$defaultSetSel.val(historyCode);
			}else {//其他情况
				$radioOther.click();
				$shopifyBackUrl2.val(url);
			}
		}else {//未保存过 勾选默认
			$radioDefault.click();
		}
		$setTrackWebsiteModal.modal('show');
	};

	//tophatter承运商下拉框切换
	var selectTophatterProviders = function (that, isJudge) {
		var $that = $(that),
			$tr = $that.closest('tr'),
			$option = $that.find('option:selected'),
			dataArr = $option.attr('data-val'),
			$tophatterServiceType = $tr.find('.tophatterServiceType'),
			option = '<option value="">请选择服务商类型</option>';

		if (dataArr) {
			try {
				dataArr = JSON.parse(dataArr);
				if (dataArr && dataArr.length) {
					$.each(dataArr, function(i, j){
						option += '<option value="' + j + '">' + j + '</option>';
					});
				}
			} catch(e){}
		}
		$tophatterServiceType.empty().html(option).trigger('chosen:updated').chosen({
			search_contains: true//注册插件
		});
	};

	//类型切换
    $(D).off('change', '.genreNotice').on('change', '.genreNotice', function() {
    	 var noticeState = $(this).attr('data-state');
		 orderTemplateMethod(+noticeState === 1 ? $('#commentContent1') : $('#commentContent'), $(this).val());
	})

	return {
		/** 根据平台选择物流方式**/
		selectProviderByPlatform: function(obj){
			var $this = $(obj),
				$tr = $this.closest('tr'),
				platform = $tr.attr('data-platform'),
				$platformOtherDiv = $tr.find('.' + platform + 'OtherDiv'),
				$platformOther = $tr.find('.' + platform + 'Other'),
				// selProviderVal = $this.val(),
				code = $this.find('option:selected').attr('data-code');

			if (platform === 'smt') {
				showSmtBack($tr, code);
			} else if (platform === 'onbuy') {
				showOnBuyBack($tr, code);
			} else if (platform === 'tophatter') {//tophatter根据选择物流承运商更新服务商数据
				selectTophatterProviders(obj)
			} else {
				if (platform === 'amazon') {//amazon根据选择物流承运商更新配送服务的数据
					DELIVERY_WITHOUT_ORDER.selectAmazonProviders(obj);
				}
				var $back = $('.' + platform + 'Back');

				if (code && code.toLocaleLowerCase() === 'other') {//selProviderVal
					$platformOtherDiv.removeClass('hide');
                    $back.addClass('p-top5');
				} else {
					$platformOtherDiv.addClass('hide');
					$platformOther.val('');
                    $back.removeClass('p-top5');
				}
			}
		},

		//amazon承运商下拉框切换
		selectAmazonProviders: function (that, isJudge) {
			var $that = $(that),
				$tr = $that.closest('tr'),
				val = $that.val(),
				$option = $that.find('option:selected'),
				dataArr = $option.attr('data-val'),
				$amazonServiceType = $tr.find('.amazonServiceType');

			$amazonServiceType[val ? 'removeClass' : 'addClass']('hide').empty();
			if (dataArr) {
				try {
					dataArr = JSON.parse(dataArr);
					if (!(dataArr && dataArr.length)) {
						dataArr = [];
					}
				} catch (e) {
					dataArr = [];
				}
			}else{
				dataArr = [];
			}
			if ($amazonServiceType.length) {
				$amazonServiceType.combobox(dataArr); //生成Amazon的配送服务的可下拉输入框
				$tr.find('input[name="amazonServiceType"]').val(''); //把隐藏域的值先清空

				$amazonServiceType.find('.combobox-ipt').addClass('w130').attr('placeholder', '请选择/输入配送服务').css({'min-height': '23px', 'height': '23px'});
				$amazonServiceType.find('.combobox-select').addClass('minW130-imp').css({'left': '0px', 'top': '24px'});
				$amazonServiceType.find('.combobox-select-down-icon').css({'height': '21px', 'top': '0', 'right': '2px'});
				$amazonServiceType.closest('.amazonServiceTypeDiv')[val === 'Other' ? 'addClass' : 'removeClass']('p-top5');
			}

			$tr.find('.amazonServiceType input.combobox-ipt').addClass('w130');
		},

		//设置追踪网址初始化
		getTrackSelectData: function (obj) {
			var $modal = $('#setTrackWebsiteModal'),
				strHtml = '<option value="">根据运单号识别</option>',// 默认下拉框选项数据
				$defaultSetSel = $('#defaultSetSel'); // 默认下拉框

			// 标记回显
			$modal.attr('data-packid', $(obj).closest('tr').attr('data-packid'));
			// 清空测试单号
			$('#testOrderInput').val('');

			commonAjaxFn('agent/getAll17TrackCarriers.json', {}, 'json', function (data) {
				if(data && !+data.code) {
					var allTrack17Carriers = data.data;
					if(allTrack17Carriers) {
						$.each(allTrack17Carriers, function (i, j) {
							strHtml += '<option value="' + j.code + '">' + j.nameZh + '</option>';
						});
					}
				}
				$defaultSetSel.html(strHtml);
				initTrackModal();
				$modal.find('.chosen-select-fixed').chosen('destroy').chosen({//把注册生成的下拉选项层改为fixed固定定位，避免被祖辈元素溢出隐藏
					search_contains: true //注册插件
				});
				$('#defaultSetSel_chosen').css('width', '200px'); //设置宽度，解决下拉搜索插件在弹层中有的时候没有宽度的问题
			}, function () {
				$defaultSetSel.html(strHtml);
				initTrackModal();
			});
		},

		//单选框切换
		tabTrackSet: function (type, url) {
			var $defaultSetBox = $('#defaultSetBox'),
				$testOrderBox = $('#testOrderBox'),
				$shopifyBack2 = $('#shopifyBack2'),
				$shopifyBackUrl2 = $('#shopifyBackUrl2');

			//清空初始化
			$defaultSetBox.find('#defaultSetSel').val('');
			$testOrderBox.find('#testOrderInput').val('');
			$shopifyBack2.find('#shopifyBackUrl2').val('');

			if (type === 'default') {
				$defaultSetBox.removeClass('hide');//显示默认设置
				$testOrderBox.removeClass('hide');//显示效果测试
				$shopifyBack2.addClass('hide');//隐藏其他
				$shopifyBackUrl2.addClass('hide');
			} else {
				$defaultSetBox.addClass('hide');//隐藏默认设置
				$testOrderBox.addClass('hide');//隐藏效果测试
				$shopifyBack2.removeClass('hide');//显示其他
				$shopifyBackUrl2.removeClass('hide');
			}
		},

		//测试订单号
		testOrder: function () {
			var $testOrderInput = $('#testOrderInput'),
				order = $.trim($testOrderInput.val()),
				code = $('#defaultSetSel').val(),
				testUrl = 'https://t.17track.net/#nums=' + order;

			if (!order) {
				commonMsgFn('请输入运单号');
				$testOrderInput.focus();
			} else {
				testUrl = code === '' ? testUrl : (testUrl + '&fc=' + code);
				W.open(testUrl, '_blank');
			}
		},

		//设置追踪网址确认
		saveSetTrackInfo: function () {
			var $setTrackWebsiteModal = $('#setTrackWebsiteModal'),
				$tr = $('#withOutPrintShippingDiv').find('tr[data-packid="' + $setTrackWebsiteModal.attr('data-packid') + '"]'),
				$input = $tr.find('input[tag="backUrl"] '),// 回显输入框
				type = $('#choseSetType').find('input[name="defaultSet"]:checked').attr('data-type');

			if (!+type) {//默认
				var code = $('#defaultSetSel').val(),
					url = 'https://t.17track.net/#nums=#TrackingNumber#',
					newStrackUrl = code === '' ? url : (url + '&fc=' + code);//新拼接的追踪网址

				$input.val(newStrackUrl).attr('title', newStrackUrl);
			} else {
				$input.val($('#shopifyBackUrl2').val());
			}
			$setTrackWebsiteModal.modal('hide');
		},

		//应用到相同平台
		changeSamePlatform: function (obj) {
			var $this = $(obj),
				$tr = $this.closest('tr'),
				platform = $tr.attr('data-platform'),
                $otherTr = $tr.siblings('tr[data-platform="' + platform + '"]'),
				names = $tr.find('td[data-names="platform"]').attr('data-values'),
				iptValues = $.trim($tr.find('input[type="radio"]:checked').val()),//发货方式
                $providerSel = $tr.find('.providerSel[name="providerSel"]'),
				providerSel = $.trim($providerSel.val()),//物流承运商
                providerCode = $providerSel.find('option:selected').attr('data-code'),
				wishCountry = $.trim($tr.find('select[name="wishCountrySel"]').val()),//wish发货地
				smtLogisticsOtherSel = $.trim($tr.find('select.smtLogisticsOtherSel').val()),//实际承运商
				$logisticsPlatFormInput = $tr.find('.' + platform + 'BackUrl'),
                logisticsVal = $.trim($logisticsPlatFormInput.val()),//追踪网址
				$logisticsName = $tr.find('input[name="' + (platform) + 'Other"]'),
				logisticsName = $.trim($logisticsName.val()),//物流名称
                tophatterServiceType = $.trim($tr.find('select.tophatterServiceType').val()),//服务商类型
				amazonServiceType = $.trim($tr.find('.amazonServiceType input.combobox-ipt').val());//amazon配送服务

            $otherTr.each(function (i, j) {
                $(this).find('input[value="' + iptValues + '"]').click();
				if (providerSel) {//更新物流承运商
					var $otherProviderSel = $(this).find('.providerSel[name="providerSel"]');

					$otherProviderSel.val(providerSel).trigger('chosen:updated');
				}
				if (platform === 'amazon' || platform === 'tophatter') $otherProviderSel.change();

                if (wishCountry) $(this).find('select[name="wishCountrySel"]').val(wishCountry).trigger('chosen:updated');//更新wish发货地
                if (smtLogisticsOtherSel) $(this).find('.smtLogisticsOtherSel').val(smtLogisticsOtherSel).trigger('chosen:updated');//更新速卖通实际承运商
                if (tophatterServiceType) $(this).find('.tophatterServiceType[name="tophatterServiceType"]').val(tophatterServiceType).trigger('chosen:updated');//更新tophatter服务商类型

                var $otherlogisticsName = $(this).find('input[name="' + (platform) + 'Other"]');

                if ($otherlogisticsName.length) {
                    $otherlogisticsName.closest('div.' + platform + 'OtherDiv')[$logisticsName.is(':visible') ? 'removeClass' : 'addClass']('hide');
                    $otherlogisticsName.val(logisticsName);//更新物流名称
                }

                var $otherLogisticsPlatFormInput = $(this).find('input.' + platform + 'BackUrl');//追踪网址

                if ($otherLogisticsPlatFormInput.length) {
                    $otherLogisticsPlatFormInput.closest('div.' + platform + 'Back')[$logisticsPlatFormInput.is(':visible') ? 'removeClass' : 'addClass']('hide')[$logisticsName.is(':visible') ? 'addClass' : 'removeClass']('p-top5');
                    $otherLogisticsPlatFormInput.val(logisticsVal).attr('title', logisticsVal);//更新追踪网址值
                }

                if (platform === 'smt' && providerCode) {//处理速卖通选择other类型的平台承运商时，显示实际承运商和追踪网址
					var $smtBacks = $(this).find('.smtBack,.smtOtherSelBack'),
						$smtBack = $smtBacks.filter('.smtBack');

                    if (!+providerCode.indexOf('Other') || !+providerCode.indexOf('OTHER')) {
						$smtBacks.removeClass('hide');
						$smtBack.addClass('m-top5');
                    }  else {
						$smtBacks.addClass('hide');
						$smtBack.removeClass('m-top5');
                    }
                }

                if (platform === 'amazon' && amazonServiceType) $(this).find('.amazonServiceType input.combobox-ipt').val(amazonServiceType).attr('title', amazonServiceType);//处理Amazon配送服务

                if (i === $otherTr.length - 1) {

					commonMsgFn('操作成功！所有「' + names + '」平台的订单都应用了此配置！', 1);
				}
            });
		},
		// 移除当前行
		removeOrder: function (obj) {
			$(obj).closest('tr').remove();
		},

		/** 无打印发货  **/
		withOutPrintShip: function () {
			var $div = $('#withOutPrintShippingDiv');
			if (!$div.find('tr:gt(0)').length) {
				$('#withOutPrintShippingModal').customModal('hide');
				return;
			}
			myjAlert.confirm({
				content: '您确认要发货吗？',
				callback: function(v) {
					if (v){
						var orderArray = [],
							numberArray = [],
							providerArray = [],
							isShipArray =[],
							wishCountryArray = [],
							trackUrlArray = [],
							serviceTypeArray = [],
							otherProviderPlatformArr = ['shopify', 'ebay', 'cd', 'amazon', 'bigcommer', 'shopbase', 'allegro', 'walmart', 'etsy', 'shopline', 'shoplazada', 'b2w'],//平台承运商选择other需要验证的平台(除了shopline、shoplazada外其他都有验证必填)
							flag = false;

						$div.find('tr:gt(0)').each(function () {
							var $this = $(this),
								platform = $this.attr('data-platform'),
								platformName = $this.find('td[data-names="platform"]').attr('data-values'),
								$providerSel = $this.find('.providerSel[name="providerSel"]'),
								providerSel = $.trim($providerSel.val()),//物流承运商
								providerCode = $providerSel.find('option:selected').attr('data-code'),//物流承运商code值
								$smtLogisticsOtherSel = $this.find('select.smtLogisticsOtherSel'),
								smtLogisticsOtherSelIsShow = $smtLogisticsOtherSel.is(':visible'),
								smtLogisticsOtherSel = (platform === 'smt' && (smtLogisticsOtherSelIsShow || (!smtLogisticsOtherSelIsShow && $smtLogisticsOtherSel.next('div.chosen-container').is(':visible')))) ? $.trim($smtLogisticsOtherSel.val()) : '',//速卖通实际承运商
								$wisgCountry = $this.find('select[name="wishCountrySel"]'),
								wishCountry = '',//wish\walmart发货地
								$tophatterServiceType = $this.find('select.tophatterServiceType'),
								tophatterServiceTypIsShow = $tophatterServiceType.is(':visible'),
								tophatterServiceType = (platform === 'tophatter' && (tophatterServiceTypIsShow || (!tophatterServiceTypIsShow && $tophatterServiceType.next('div.chosen-container').is(':visible')))) ? $.trim($tophatterServiceType.val()) : '',//tophatter服务商类型
								$amazonServiceInput = $this.find('.amazonServiceType input.combobox-ipt'),
								amazonServiceType = (platform === 'amazon' && $amazonServiceInput.is(':visible')) ? $.trim($amazonServiceInput.val()) : '',//amazon配送服务
								$logisticsName = $this.find('input[name="' + (platform) + 'Other"]'),
								logisticsName = $logisticsName.is(':visible') ? $.trim($logisticsName.val()) : '',//物流名称
								$logisticsPlatFormInput = $this.find('input.' + platform + 'BackUrl'),
								logisticsPlatFormInput = $logisticsPlatFormInput.is(':visible') ? $.trim($logisticsPlatFormInput.val()) : '',//追踪网址
								$tracingNumber = $this.find('input[name="tracingNumber"]'),
								tracingNumber = $.trim($tracingNumber.val()),//跟踪号
								orderId = $tracingNumber.data('id'),
								isShip = $this.find('input[type="radio"]:checked').val(),//发货方式
								serviceType = '';

							if (!smtLogisticsOtherSel) smtLogisticsOtherSel = '';
							if (!wishCountry) wishCountry = '';
							if (!tophatterServiceType) tophatterServiceType = '';
							if (!logisticsPlatFormInput) logisticsPlatFormInput = '';

							//平台物流承运商
							if (!providerSel) {
								flag = true;
								commonMsgFn('请选择平台物流承运商');
								$providerSel.next('.chosen-container').find('input:text').focus();
								return false;
							}

							//wish平台发货地必填
							if (platform === 'wish') {
								var wisgCountryIsShow = $wisgCountry.is(':visible');

								//兼容下拉框是否需要取值的情况（如果未注册上下拉插件，则判断原生节点是否显示）
								if ((!wisgCountryIsShow && $wisgCountry.next('div.chosen-container').is(':visible'))|| wisgCountryIsShow) {
									wishCountry = $.trim($wisgCountry.val()); //wish发货地
								}
								if (!wishCountry) {
									flag = true;
									$wisgCountry.next('.chosen-container').find('input:text').focus();
									commonMsgFn('请选择Wish发货地');
									return false;
								}
							} else if (platform === 'walmart') { //walmart平台发货地必填
								var $walmartCountryCode = $this.find('select[name="walmartCountryCode"]'),
									walmartCountryCodeIsShow = $walmartCountryCode.is(':visible');

								if ((!walmartCountryCodeIsShow && $walmartCountryCode.next('div.chosen-container').is(':visible')) || walmartCountryCodeIsShow) {
									wishCountry = $.trim($walmartCountryCode.val()); //walmart发货地
								}

								if (!wishCountry) {
									flag = true;
									$walmartCountryCode.next('.chosen-container').find('input:text').focus();
									commonMsgFn('请选择Walmart发货地');
									return false;
								}
							}
							wishCountryArray.push(wishCountry);

							//物流名称
							//如果物流承运商选择的是other类型的，需要验证某些平台必填物流名称
							if (otherProviderPlatformArr.indexOf(platform) > -1 && (!+providerCode.indexOf('Other') || !+providerCode.indexOf('OTHER'))) {
								var name = logisticsName;

								if ($logisticsName.is(':visible') && platform !== 'shoplazada' && !logisticsName) {//必填物流名称
									flag = true;
									$logisticsName.focus();
									commonMsgFn('选择' + platformName + '自定义物流方式，物流名称不能为空');
									return false;
								}
								if (platform === 'shoplazada') {//shoplazada承运商选other非必填，如果物流名称为空，就传other
									name = !logisticsName ? providerSel : logisticsName;
								}

								providerArray.push(name);
							} else if('tiktok' === platform){
								providerArray.push(providerCode) ;
							} else {//没有选择other，传物流承运商
								providerArray.push(providerSel);
							}

							if (platform === 'smt') {
								if ($logisticsPlatFormInput.is(':visible') && (!+providerCode.indexOf('Other') || !+providerCode.indexOf('OTHER'))
									&& !logisticsPlatFormInput) {
									flag = true;
									$logisticsPlatFormInput.focus();
									commonMsgFn('选择速卖通自定义物流方式，追踪网址不能为空');
									return false;
								}
								serviceType = smtLogisticsOtherSel;
							}

							if (platform === 'amazon') {
								if (amazonServiceType.length > 50) {//Amazon配送服务长度不能超出50个字符
									flag = true;
									$amazonServiceInput.focus();
									commonMsgFn('Amazon配送服务长度不能超过50字符');
									return false;
								}
								serviceType = amazonServiceType;
							}

							//tophatter服务商类型（所有物流都必填）
							if (platform === 'tophatter') {
								if (!tophatterServiceType) {
									flag = true;
									$tophatterServiceType.focus();
									commonMsgFn('请选择tophatter服务商类型');
									return false;
								}
								serviceType = tophatterServiceType;
							}

							//追踪网址
							if (logisticsPlatFormInput && logisticsPlatFormInput.length > 100) {
								flag = true;
								$logisticsPlatFormInput.focus();
								commonMsgFn('追踪网址不能操作100个字符');
								return false;
							}
							trackUrlArray.push(logisticsPlatFormInput);

							serviceTypeArray.push(serviceType);

							//跟踪号
							if (!tracingNumber) {
								flag = true;
								$tracingNumber.focus();
								commonMsgFn('物流跟踪号不能为空');
								return false;
							}
							numberArray.push(tracingNumber);
							orderArray.push(orderId);

							//发货方式
							isShipArray.push(isShip);
						});
						if (flag) return;

						commonAjaxFn('package/withOutPrintShip.json', {
							packageIds: orderArray.join(','),
							tracingNumbers: numberArray.join(','),
							providerNames: providerArray.join(','),//
							isShipStr: isShipArray.join(','),//发货方式
							wishCountrys: wishCountryArray.join(','),//wish\walmart发货地
							trackUrls: trackUrlArray.join(','),//追踪网址
							serviceTypes: serviceTypeArray.join(',')//tophatter服务商类型、速卖通实际承运商、amazon配送服务
						}, 'json', function (data) {
							if (!+data.code) {
								$('#withOutPrintShippingModal').modal('hide');
								var successList = data.bor.successList;

								batchReturnProcess(successList, data.bor.failList, getSuccessMsg(successList));
								refreshAjaxPage();
							} else {
								commonMsgFn(data.msg ? data.msg : '发货失败');
							}
						});
					}
				}
			})
		},

		//存为模板
		saveTemplateMethod: function (state) {
			var $commentType = $('#commentType'),
				$bgComment = $('#commentColorDiv').find('.bgCommentFocus'),
				$commentContent = $('#commentContent'),
				paramObj = {} , type = '', content = '';

			if(state === 1) {
				$commentType = $('#commentType1');
				$bgComment = $('#commentColorDiv1').find('.bgCommentFocus');
				$commentContent = $('#commentContent1');
			}
			type = $commentType.val();
			content = $commentContent.val();

			if(!content) {
				MYJ.message.error('请填写内容');
				return;
			}

			paramObj = {
				type: type,
				color: type === 'sys_picking' ? $bgComment.attr('data-val') : '',
				remark: content
			}

			MYJ.ajax({
				url: 'order/remark/config/save.json',
				data: JSON.stringify(paramObj),
				dataType: 'json',
				contentType: 'application/json',
				success: function (res) {
					if(!+res.code) {
						MYJ.message.success('保存模板成功');
						orderTemplateMethod($commentContent, $commentType.val());
					} else {
						MYJ.message.error(res.msg);
					}
				}
			});
		}
	}

}(jQuery, window, document));

/*手工订单改版后的新版交互相关方法*/
var MANUAL_ORDER = (function ($, W, D) {
	var locHref = gitWinLocHref(),
		$emptyDiv = $('<div></div>'),
		$loading = $('#loading'),
		comData = {
			html: {
				trStr: '<tr><td class="f-center p10 border-right1">' +
					'<input type="hidden" value="" placeholder="" name="productImg" />'+
					'<input type="hidden" value="" placeholder="" name="stockProductId"/>' +
					'<input type="hidden" value="" placeholder="" name="stockProductPrice"/>' +
					'<input type="text" class="form-control inline-block w150 p-left10 p-right10 m-right10" name="proSku" maxlength="100"/>' +
					'<a href="javascript:" onclick="MANUAL_ORDER.productSelcet(this);">选择商品SKU</a>' +
					'</td>' +
					'<td class="f-center p10 border-right1">' +
					'<input type="text" class="form-control inline-block w150 p-left10 p-right10" placeholder="非必填" name="attr" maxlength="250"/>' +
					'</td>' +
					'<td class="f-center p10 border-right1">' +
					'<input type="text" class="form-control inline-block w230 p-left10 p-right10" value="" placeholder="请输入销售链接" name="productUrl" maxlength="2000"/>' +
					'</td>' +
					'<td class="f-center p10 border-right1">' +
					'<input type="text" class="form-control inline-block w130 p-left10 p-right10" name="count" oninput="clearMistakeNumber(this);" maxlength="20"/>' +
					'</td>' +
					'<td class="f-center p10 border-right1">' +
					'<input type="text" class="form-control inline-block w130 p-left10 p-right10" name="price" oninput="clearNoNumAndMinus(this);" maxlength="20"/>' +
					'</td>' +
					'<td class="removeTr f-center p10"><a href="javascript:" cid="removeTr">移除</a></td>' +
					'</tr>'
			}
		};

	//公用ajax请求方法
	var commonAjaxFn = function (url, ajaxData, dataType, successCall, errorCall, type, async) {
		$loading.modal('show');
		$.ajax({
			type: type ? type : 'POST',
			url: locHref + url,
			data: ajaxData,
			dataType: dataType,
			async: !async,
			success: function(data){
				$loading.modal('hide');
				successCall && typeof successCall === 'function' && successCall(data);
			},
			error: function(){
				$loading.modal('hide');
				if(errorCall && typeof errorCall === 'function'){
					errorCall();
				}else {
					showNetError();
				}
			}
		});
	};

	//公用报错提示方法
	var commonMsgFn = function (msg, type, isText) {
		$.fn.message({type: type ? 'success' : 'error', msg: msg, isText: !!isText});
	};

	//清空节点公用方法
	var commonEmptyDomFn = function ($dom) {
		if($dom.length) $emptyDiv.append($dom).empty();
	};

	return {
		init: function () {
			var that = this;

			//产品信息 数量、单价失焦时自动计算产品总金额和总金额（加运费）
			$(D).off('focusout', 'input[name="count"],input[name="price"]')
				.on('focusout', 'input[name="count"],input[name="price"]', function () {
				var orderNumArr = $('input[name="count"]'),
					priceArr = $('input[name="price"]'),
					freightFee = +($('#shipAmount').val()),
					totalPrice = 0,
					i;

				for (i = 0; i < orderNumArr.length; i++) {
					var orderNum = $(orderNumArr[i]).val(),
						price = $(priceArr[i]).val();

					if (isNaN(orderNum))  orderNum = 1;
					if (isNaN(price)) price = 0;

					totalPrice += orderNum * price;
				}
				$('#totalPriceSpan').text(totalPrice.toFixed(2));
				$('#totalPriceSpan2').text((totalPrice + freightFee).toFixed(2));
			});

			//产品信息移除当前行
			$(D).off('click', 'a[cid="removeTr"]').on('click', 'a[cid="removeTr"]', function () {
				$(this).closest('tr').remove();
				var orderNumArr = $('input[name="count"]'),
					priceArr = $('input[name="price"]'),
					freightFee = +($('#shipAmount').val()),
					totalPrice = 0;

				for (var i = 0; i < orderNumArr.length; i++) {
					var orderNum = $(orderNumArr[i]).val(),
						price = $(priceArr[i]).val();

					if (isNaN(orderNum)) orderNum = 1;
					if (isNaN(price)) price = 0;
					totalPrice += orderNum * price;
				}
				$('#totalPriceSpan').text(totalPrice.toFixed(2));
				$('#totalPriceSpan2').text((totalPrice + freightFee).toFixed(2));
			});

			//注册增加一行点击事件
			$(D).off('click', '#buildManualOrder a[cid="addTr"]').on('click', '#buildManualOrder a[cid="addTr"]', function () {
				$('#buildManualOrder .productInfoBox table').append(comData.html.trStr);
			});

			// 注册点击修改采购成本按钮事件
			$(D).off('click', '#freightFeeHoverDiv a.editFreightFee').on('click', '#freightFeeHoverDiv a.editFreightFee', function () {
				that.editFreightFeeFn();
				$('#varintUpdateInput').select();
			});
		},

        /** 显示导入手工订单 **/
        showImportHandOrder: function() {
			var txtStr = '请选择您要导入的文件，支持EXCEL格式';
            importShippingUp.cancel('*');
            $('#importShippingFileName').html(txtStr);
            $('#importHandOrderModal').modal('show');
        },
		changeFileType: function(type) {
        	var $systemFieldBox = $('.systemFieldBox'),
				$customFieldBox = $('.customFieldBox');
        	if (type === 1) {
				$systemFieldBox.removeClass('hide');
				$customFieldBox.addClass('hide');
			} else {
				$systemFieldBox.addClass('hide');
				$customFieldBox.removeClass('hide');
			}
		},

		/** 显示要引用的订单列表**/
		showQueteOrderList: function () {
			var url = 'package/list.htm?shopId=-1&state=&platform=&isSearch=1&searchType=orderId&authId=-1&' +
				'isVoided=-1&ruleId=-1&applyType=&applyStatus=&printJh=-1&printMd=-1&commitPlatform=&productStatus=&' +
				'jhComment=-1&storageId=0&isOversea=-1&isFree=-1&isBatch=-1&history=&listType=1',
				$shopGroupId = $('#shopGroupId'),
				shopGroupId = $shopGroupId.length ? $.trim($shopGroupId.val()) : '';

			if (shopGroupId) url += '&shopGroupId=' + shopGroupId;//如果选中了店铺分组，则加上店铺分组参数作为筛选条件
			$('#searchValue').val('');//搜索内容
			$('#searchType').val('orderId');//搜索字段
			$('#searchState').val('');//状态
			$('#searchPlatform').val('');//平台
			$('#keepState').data('url', url);
			url += '&pageNo=1&pageSize=100';

			commonAjaxFn(url, {}, 'html', function (data) {
				$('#quotePageList').html(data);
				quoteInitPage();
				$('#orderQuoteModal').modal('show');
			});
		},

		/** 增加手工订单 **/
		addHandOrder: function () {
			var $handOrderId = $('#handOrderId'),
				orderIdStr = $.trim($handOrderId.val()),
				$manuallyOrderShopId = $('#manuallyOrderShopId'), //手工订单店铺账号id
				skus = $("input[name='proSku']"),
				orderNums = $("input[name='count']"),
				prices = $("input[name='price']"),
				shipAmount = $("input[name='shipAmount']"),
				reg = /^\d+(\.\d{1,2})?$/,
				idReg = /[^\w-]/g;
			// 应用新组件，不存在option节点了
			if (!$manuallyOrderShopId.val()) {
				commonMsgFn('请选择店铺账号');
				$manuallyOrderShopId.focus();
				return;
			}

			if (!orderIdStr) {
				commonMsgFn('请输入订单号');
				$handOrderId.focus();
				return;
			}
			if (idReg.test(orderIdStr)) {
				commonMsgFn('订单ID只能输入字母、数字、中划线、下划线');
				$handOrderId.focus();
				return;
			}
			if (validateCustom(skus, '', 0, '请输入产品SKU')) return;
			if (validateCustom(skus, '', 4, 'sku不能重复')) return;
			if (validateCustom(orderNums, /^[0-9]*$/, 1, '请输入数量', '数量请输入大于0的整数')) return;
			if (validateCustom(prices, reg, 3, '请输入单价', '单价请输入大于0的数字,小数点保留1-2位')) return;
			if (validateCustom(shipAmount, reg, 3, '请输入运费', '运费请输入大于等于0的数字,小数点保留1-2位')) return;

			// 保存选中的币种
			saveChooseCurrency();

			commonAjaxFn('package/addHandOrder.json', $('#handOrderForm').serialize(), 'json', function (data) {
				if (!+data.code) {
					$('#handOrderPackageSpan').html(data.packageNumber);
					$('#handOrderStateSpan').html( data.state === 'approved' ? '待处理' : '待审核');
					$('#createHandOrderMsgModal').modal('show');
				} else {
					commonMsgFn(data.msg);
				}
			});
		},

		/** 选择产品SKU **/
		productSelcet: function (obj) {
			$('#productsOrderQuoteModal').modal('show');
			productSkuObj = obj;
			ajaxGetStockProduct(1);
		},

		// 点击后出现更新、取消操作
		editFreightFeeFn: function () {
			var freightFeeVal = $('#shipAmount').val(),
				$editHtml = $('<div class="f-center w100 absolute position-t0 bg-gray variantBotton" style="right:0;z-index: 1;">' +
					'<button type="button" class="button btn-determine btn-sm"' +
					'onclick="MANUAL_ORDER.updateFreightFeeSubmit();">确定</button>' +
					'<button type="button" class="button btn-gray border-rad2 m-left5 btn-sm" onclick="MANUAL_ORDER.editFreightFeeRestartInput();">取消</button></div>'),
				$iptHtml = $('<input id="varintUpdateInput" type="text" maxlength="9" oninput="clearNoNumAndMinus(this);" ' +
					'onkeydown="MANUAL_ORDER.buttonFunc(event);" class="w-full"' +
					'style="height:24px;line-height:24px;padding:0 3px;" value="' + $.trim(freightFeeVal) + '"/><br>'); // 费用正则

			this.editFreightFeeRestartInput();
			$editHtml.prepend($iptHtml);
			$('#freightFeeHoverDiv').addClass('hide').after($editHtml);
		},

		// 取消修改运费,移除样式
		editFreightFeeRestartInput: function() {
			commonEmptyDomFn($('.variantBotton'));
			$('#freightFeeHoverDiv').removeClass('hide');
		},

		// ESC、ENTER
		buttonFunc: function(e) {
			var keyCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;

			if (+keyCode === 13) this.updateFreightFeeSubmit();//ENTER键
			if (+keyCode === 27) this.editFreightFeeRestartInput();//ESC键
		},

		//确定修改运费
		updateFreightFeeSubmit: function() {
			var freightFee = $.trim($('#varintUpdateInput').val()),
				reg = /^[0-9,.]*$/,
				$totalPriceSpan = $('#totalPriceSpan'),
				totalProductPrice = +$.trim($totalPriceSpan.text());//产品总金额

			if (!freightFee) {
				commonMsgFn('请输入运费');
				return;
			}
			if (!reg.test(freightFee)) {
				commonMsgFn('请输入正确的格式');
				return;
			}

			$('#freightFeeHoverDiv').removeClass('hide').find('#freightFee').text((+freightFee).toFixed(2));
			$('#shipAmount').val((+freightFee).toFixed(2));
			$('#totalPriceSpan2').text((Number(totalProductPrice) + Number(freightFee)).toFixed(2));
			this.editFreightFeeRestartInput();
		},

		//关闭手工订单页面
		winClose: function () {
			myjAlert.confirm({
			    modalWidth: 400, //弹层宽度
			    content: '<div>关闭后，已输入的订单内容将清空。</div>' +
					'<div>您确定要关闭吗？</div>', //弹层内容
			    callback: function (v) { //确认/取消按钮回调函数，v=true确认回调|false取消回调
			        if (v) {
						W.close();
			        }
			    }
			});
		}
	};
}(jQuery, window, document));


//编辑附加信息(回显)
var editAdditionalInfo = function (packageId) {
  var $loading = $('#loading'),
      authId = $('#updateShipInfoAuthSelect').val(),
      $modal = $('#dhlEditAdditionalInfoModal');
    $loading.modal('show');
    $.ajax({
      type: 'POST',
      url: gitWinLocHref() + 'order/getAdditionalInformation.json',
      async: false,
      data:{
        packageId: packageId,
        authId: authId
      },
      dataType: 'json',
      success:function(data){
        $loading.modal('hide');
        if (!+data.code) {
          var info = data.data;
          if (info) {
            $('select[name="receiverType"]').val(info.receiverType);
            $('input[name="freight"]').val(info.freight);
            $('input[name="insurance"]').val(info.insurance);
            var isEditTradePort = info.isEditTradePort;

            isEditTradePort = +isEditTradePort === 1;
            $('#isEditTradePort').prop('checked', isEditTradePort);
            editTradeTermsAndPortName();//根据是否可编辑的状态对贸易条款、港口名称进行初始化
            if (isEditTradePort) {
              $('select[name="tradeTerms"]').val(info.tradeTerms);
              $('input[name="portName"]').val(info.portName);
            }
          }
        }
      },
      error: function () {
        $loading.modal('hide');
      }
    });
  //换物流时，因为运单号有可能没保存，所以提示下面信息
  if ($('#updateLogisticsInformation').is(':visible')) {
	  var tipContent = $('#orderStatus').val() === 'processed' ? '编辑内容后，必须将订单打回待处理并重新「申请运单号」后才能生效！直接在该页面「获取跟踪号」不会生效' : '编辑内容后，必须「更换运单号」才能生效！';
    myjAlert.alert({
      'close' : '<span></span>',
      'width' : 450,
      'content':'<span style="font-size:14px;color:red"><span style="font-weight: 600">重要提示：</span>' + tipContent + '</span>',
      'enter' :'我知道了'
    });
  }

  $modal.attr({'packageId': packageId, 'authId': authId}).modal('show');

};

//编辑贸易条款和港口名称
var editTradeTermsAndPortName = function (type) {
  var isChecked = $('#isEditTradePort').is(':checked');

  if (type && type === 'batch') {//批量编辑
    var $form = $('#postPonyForm');

    //批量的则只禁用操作,不清除数据
    $form.find('td select[name="tradeTerms"]').prop('disabled', !isChecked);
    $form.find('td input[name="portName"]').prop('disabled', !isChecked);
    $('.tradeTermsBatchEditBtn,.portNameBatchEditBtn').find('a')[isChecked ? 'removeClass' : 'addClass']('no-drop');
  } else {//单个编辑
    $('.tradeTermsBox,.portNameBox')[isChecked ? 'removeClass' : 'addClass']('hide');
    if (!isChecked) {//取消编辑则进行初始化清空
      $('select[name="tradeTerms"]').val('');
      $('input[name="portName"]').val('');
    }
  }
};

//批量修改操作
var batchEditDhkModalData = function (type, obj) {
  if ($(obj).hasClass('no-drop')) return;//禁用则不再执行批量操作
  var titleStr = '',
      $modal = $('#batchEditDhkDataModal');

  $modal.find('input,select').val('');
  $('.batchEditDivBox').addClass('hide');
  switch (type) {
    case 'receiverType'://收件人类型
      titleStr = '收件人类型';
      break;
    case 'freight'://运费
      titleStr = '运费';
      break;
    case 'insurance'://保险费
      titleStr = '保险费';
      break;
    case 'tradeTerms'://贸易条款
      titleStr = '贸易条款';
      break;
    case 'portName'://港口名称
      titleStr = '港口名称';
      break;
  }
  $('#batchEditDhkModalTitel').text(titleStr);
  $('#actionType').val(type);
  $('#' + type + 'Div').removeClass('hide');
  $modal.modal('show');
};
//批量选择物流方式弹层里面的批量修改操作
var batchEditDhkModalDataSubmit = function () {
  var actionType = $('#actionType').val(),
      inputType = (actionType === 'receiverType' || actionType === 'tradeTerms') ? 'select' : 'input',
      editVal = $('#' + actionType + 'Div').find(inputType).val().trim();

  $('#postPonyForm tbody').find('tr').find(inputType + '[name="' + actionType + '"]').val(editVal);
  $('#batchEditDhkDataModal').modal('hide');
};

//关闭批量选择物流方式弹层
var closeBatchEditDhkModal = function () {
  $('#batchEditDhkDataModal').modal('hide');
};

//编辑附加信息保存提交
var additionalInfoSubmit = function () {
  var $loading = $('#loading'),
      $modal = $('#dhlEditAdditionalInfoModal'),
      packageId = $modal.attr('packageId'),
      authId =  $modal.attr('authId'),
      receiverType = $.trim($('select[name="receiverType"]').val()),
      freight = $.trim($('input[name="freight"]').val()),
      insurance = $.trim($('input[name="insurance"]').val()),
      tradeTerms = $.trim($('select[name="tradeTerms"]').val()),
      portName = $.trim($('input[name="portName"]').val());

  $loading.modal('show');
  $.ajax({
    type: 'POST',
    url: gitWinLocHref() + 'order/editAdditionalInformation.json',
    async: false,
    data:{
      packageId: packageId,
      authId: authId,
      isEditTradePort: $('#isEditTradePort').is(':checked') ? 1 : 0,//是否编辑贸易条款/港口名称
      receiverType: receiverType,//收件人类型
      freight: freight,//运费
      insurance: insurance, //保险费
      tradeTerms: tradeTerms,//贸易条款
      portName: portName//港口名称
    },
    dataType: 'json',
    success:function(data){
      $loading.modal('hide');
      if(!+data.code) {
        $.fn.message({type: 'success', msg: '保存DHL附加信息成功'});
        $modal.modal('hide');
      } else {
        $.fn.message({type: 'error', msg: data.msg ? data.msg : '保存DHL附加信息失败'});
      }
    },
    error: function () {
      $loading.modal('hide');
      showNetError();
    }
  });
};

//关闭编辑附加信息弹层
var closeAdditionalInfoModal = function () {
  $('#dhlEditAdditionalInfoModal').modal('hide');
};

//店小秘信息添加来源URL删除
$(document).off('click', '.removeTrMark').on('click', '.removeTrMark', function () {
	$(this).closest('tr').remove();
	$('#addSourceTab tr[sourceUrlMarkTr="sourceUrlMarkTr"]').each(function (i) {
		$(this).find('span').first().text(i + 1);
		$(this).find('[name="sourceUrl"]').attr('sourceUrl' + i + 1);
	});
	showAdd(2); //调用myj.js里面的方法
});
//店小秘信息添加来源URL
var addSourceInput = function () {
	var prefix = 'sourceUrl',
		urlLength = $('tr[sourceUrlMarkTr="sourceUrlMarkTr"]').length,
		//来源URL添加节点
		sourceUrlHTML = '<tr sourceUrlMarkTr="sourceUrlMarkTr">' +
		'<td></td><td class="source-url-info p5">' +
		'<div class="input-group w400 fl orderSource"><div class="input-group-addon">' +
		'<a><span class="source-url-index">&{urlLength}</span></a></div>' +
		'<input class="form-control" id="sourceUrl&{urlLength}" name="sourceUrl" type="text" maxlength="400"' +
		' placeholder=""/>' +
		'<div class="input-group-addon pointer">' +
		'<a href="javascript:" onclick="jumpSourceUrl(this);"><span>访 问</span></a></div></div>' +
		'<span class="source-url-remove glyphicon glyphicon-remove removeTrMark"></span>' +
		'</td></tr>';
	if (urlLength < 5) {
		$('#addSourceTab').append(sourceUrlHTML.format({urlLength: urlLength + 1}));
		showAdd(1); //调用myj.js里面的方法
	}
};
//店小秘信息添加来源URL访问
var jumpSourceUrl = function (obj) {
	var jumpUrl = $.trim($(obj).closest('.orderSource').find('input[name="sourceUrl"]').val());
	if ($.trim(jumpUrl)) {
		if (jumpUrl.indexOf('http') === -1 && jumpUrl.indexOf('HTTP') === -1 && jumpUrl.indexOf('https') === -1) {
			jumpUrl = 'http://' + jumpUrl;
		}
		window.open(jumpUrl);
	}
};
// 获取添加来源弹层内的url
var getSourceUrl = function (orderId, num) {
	var $loading = $('#loading'),
		$modal = $('#addSourceModal'),
		hidId = '#relationListHidden_' + orderId + '_' + num,
		goodsId = $(hidId).attr('proid'),//商品ID,
		platform = $(hidId).attr('platform');//平台
	$loading.modal('show');
	$.ajax({
		type: 'POST',
		url: gitWinLocHref() + 'order/getProductAndGoodsSourceUrl.json',
		data: {
			orderProductId: $(hidId).attr('orderProductId'),//订单产品ID,
			goodsId: goodsId,
			platform: platform
		},
		dataType: 'json',
		success: function (data) {
			$loading.modal('hide');
			if(!+data.code){
				var productSourceUrl = data.productSourceUrl ? data.productSourceUrl.split('|') : '',// 现有产品来源
					goodsSourceUrl = data.goodsSourceUrl ? data.goodsSourceUrl.split('|') : '',// 现有商品来源
					sourceUrlStr = '<div class="p-top5 nowSourceUrl"><a class="white-space-nowrap" href="&{sourceUrl}" target="_blank">&{sourceUrl}</a></div>',//现有来源url模板
					productUrlStr = '',// 现有产品来源Html
					goodsUrlStr = '';// 现有商品来源Html

                // 弹层保存提交时需要提交的几个字段暂存在#addSourceTab节点上，保存提交的时候再取值
				$('#addSourceTab').attr({'data-platformProductId': data. platformProductId, 'data-goodsId': goodsId, 'data-platform': platform});

				// 生成现有来源
                if(productSourceUrl){
                    $.each(productSourceUrl, function (i, j) {
                        productUrlStr += sourceUrlStr.format({sourceUrl: j})
                    });
                }
                if(goodsSourceUrl){
                    $.each(goodsSourceUrl, function (i, j) {
                        goodsUrlStr += sourceUrlStr.format({sourceUrl: j})
                    });
                }
				$modal.find('.productSourceUrl').html(productUrlStr);
				$modal.find('.goodsSourceUrl').html(goodsUrlStr);
				// 清空初始化弹层
                $modal.find('.addSourceFrom').prop('checked', true);
				$('input[name="sourceUrl"]').val('');
				$modal.find('.removeTrMark').closest('tr').remove();
                showAdd(2); //调用myj.js里面的方法

				$modal.modal('show');
			}else{
				$.fn.message({type: 'error', msg: data.msg});
			}
		},
		error: function () {
			$loading.modal('hide');
			showNetError();
		}
	});
};
//添加来源弹层保存事件
var addSourceConfirm = function () {
    var $modal = $('#addSourceModal'),
		$loading = $('#loading'),
        addSourceFromArr = [],
        sourceUrls = '',
        platformProductId = $('#addSourceTab').attr('data-platformProductId'),// 订单产品对应的在线产品ID
		flag = true;
    $('.addSourceFrom:checked').each(function () {//获取添加到勾选的是产品还是商品
        addSourceFromArr.push($(this).val());
    });
    if(!addSourceFromArr.length){
		$.fn.message({type: 'error', msg: '产品和商品至少勾选1项'});
		return;
	}
    $('tr[sourceurlmarktr="sourceUrlMarkTr"] input[name="sourceUrl"]').each(function () {//获取来源URL
        var value = $.trim($(this).val());
        if(!value){
			$.fn.message({type: 'error', msg: '来源URL不能为空'});
			$(this).focus();
			flag = false;
			return false;
		}
        if(!urlF(value)){
            $.fn.message({type: 'error', msg: '网址不符合要求，输入的网址不是以http:// 或 https:// 开头的URL地址或者包含了特殊字符！'});
            $(this).focus();
            flag = false;
            return false;
        }
    	sourceUrls += (!sourceUrls ? '' : '|') + $.trim($(this).val());
    });

    if(flag){
		var proIsCheck = addSourceFromArr.indexOf('0') !== -1,// 是否勾选了添加产品
            goodsIsCheck = addSourceFromArr.indexOf('1') !== -1,// 是否勾选了添加商品
            sourceUrlLen = $('tr[sourceurlmarktr="sourceUrlMarkTr"]').length,//来源URL条数
			productUrlLen = $modal.find('.productSourceUrl').find('.nowSourceUrl').length,//现有产品来源URL条数
			goodsUrlLen = $modal.find('.goodsSourceUrl').find('.nowSourceUrl').length;//现有商品来源URL条数
		if(proIsCheck && !platformProductId){
            $.fn.message({type: 'error', msg: '订单产品对应的在线产品不存在，请取消勾选添加产品'});
            return;
        }
        if(proIsCheck){
			if((sourceUrlLen + productUrlLen) > 5){
				$.fn.message({type: 'error', msg: '产品URL总数超过5条，请到产品编辑页删减后再试'});
				return;
			}
		}
		if(goodsIsCheck){
			if((sourceUrlLen + goodsUrlLen) > 5){
				$.fn.message({type: 'error', msg: '商品URL总数超过5条，请到商品编辑页删减后再试'});
				return;
			}
		}
	}

	if(!flag) return;
    $loading.modal('show');
    $.ajax({
        type: 'POST',
        url: gitWinLocHref() + 'order/addProductAndGoodsSourceUrl.json',
        data: {
            platformProductId: platformProductId,
            goodsId: $('#addSourceTab').attr('data-goodsId'),
            platform: $('#addSourceTab').attr('data-platform'),
            addSourceFrom: addSourceFromArr.join(','),// 添加到: 1产品 2商品
            sourceUrls: sourceUrls // 来源URL: 以|为分隔符的字符串
        },
        dataType: 'json',
        success: function (data) {
            $loading.modal('hide');
			if(!+data.code){
				$.fn.message({type: 'success', msg: '添加成功'});
				$('#addSourceModal').modal('hide');
			}else{
				$.fn.message({type: 'error', msg: data.msg});
			}
        },
        error: function () {
            $loading.modal('hide');
			showNetError();
        }
    });
};

//批量禁止处理、 批量取消禁止处理方法共用 1：禁止  0：取消禁止
var showBatchForbidHandle = function (actionType) {
	var packageIds = getCheckBoxValByName('packageId'),
		$loading = $('#loading');

	if (!packageIds) {
		$.fn.message({type: 'error', msg: '请至少选择一个订单'});
		return;
	}
	$loading.modal('show');
	$.ajax({
		type: 'POST',
		url: gitWinLocHref() + 'order/batchForbidCancel.json',
		data: {
			packageIds: packageIds,
			type: actionType  //1:批量禁止处理   0：取消禁止处理
		},
		dataType: 'html',
		success: function (data) {
			$loading.modal('hide');
			if (data) {
			    if (typeof data === 'string') data = JSON.parse(data);
                if (!+data.code) {
                    var successList = data.bor.successList,
                        failList = data.bor.failList;

                    batchReturnProcess(successList, failList, '');
                } else {
                    $.fn.message({type: "error", msg: data.msg});
                }
                refreshAjaxPage();//刷新列表页
            }
        },
		error: function () {
			$loading.modal('hide');
		}
	});
};

// 批量填充COD金额
var showBatchUpdateCOD = function () {
	var packageIds = getCheckBoxValByName('packageId'),
		$butchUpeateCodModal = $('#butchUpeateCodModal');
	if (!packageIds) {
		$.fn.message({type: 'error', msg: '请至少选择一条数据'});
		return;
	}
	$butchUpeateCodModal.modal('show').attr('data-id', packageIds);
};
var confirmUpdateCod = function () {
	var $butchUpeateCodModal = $('#butchUpeateCodModal'),
		packageIds = $butchUpeateCodModal.attr('data-id');
	MYJ.ajax({
		url: 'package/batchSetCodAmount.json',
		data: {
			packageIds: packageIds
		},
		pointKey: 'batchSetCodAmount', //防连点key名
		success: function (data) {
			if (!+data.code) {
				$.fn.message({type: 'success', msg: 'COD金额更新成功'});
				$butchUpeateCodModal.modal('hide');
				refreshAjaxPage();
			} else {
				$.fn.message({type: 'error', msg: data.msg});
			}
		}
	});
}

var SHOW_BATCHINWAYBILLNO = (function(){
	return {
		state: false,
		authId: 0,
		title: '',
		hideButton: function() {
			this.state = false;
			$('.smtInWayBillNo').addClass('hide');
		},
		showButton: function() {
		    if (this.state) {
			    $('.smtInWayBillNo').attr({
					'data-auth-id': this.authId,
					'data-auth-text': this.title
				}).removeClass('hide');
            } else {
                $('.smtInWayBillNo').addClass('hide');
            }
		},
		showModal: function(obj) {
			var packageIds = getCheckBoxValByName("packageId"),
				authId = $(obj).attr('data-auth-id'),
				authText = $(obj).attr('data-auth-text');

			if (packageIds === '') {
				$.fn.message({type: "error", msg: "请至少选择一个速卖通订单"});
				return;
			}
			MYJ.ajax({
				url: 'order/showBatchSmtOnline.htm',
				data: {
					packageIds: packageIds,
					authId: authId
				},
				dataType: 'html',
				success: function (data) {
					var $smtOnLineShip = $('#smtOnLineShip');
					$('#batchUpdateProvider').modal('hide');
					$smtOnLineShip.empty().html(data);
					$('#loading').modal('hide');
					$smtOnLineShip.find("span[data-name='authText']").html('- ' + authText);
					$smtOnLineShip.modal('hide').modal('show');
				}
			});
		}
	}
})();

//库存详情、占用详情方法
var INVENTORY_DETAIL_FN = (function ($, D, W) {

	return {
		//显示库存详情弹层
		showInventoryDetailModal: function (packageId) {
			var $loading = $('#loading');

			$loading.modal('show');
			$.ajax({
				type: 'POST',
				url: gitWinLocHref() + 'order/lockStockDetail.htm',
				data: {
					packageId: packageId
				},
				dataType: 'html',
				success: function (data) {
					$loading.modal('hide');
					$('#lookStockDetailModal').html(data).modal('hide').modal('show');
                    //注册图片放大
                    $('div.imgDivIn').picZoom({
                        imgWidth: '296',
                        imgHeight: '296',
                        divWidth: '300',
                        divHeight: '300'
                    }, 500);
				},
				error: function () {
					$loading.modal('hide');
				}
			});
		},

		//查看库存明细（查看其他的库存）
		viewOtherInventoryDetail: function (obj) {
			var dataType = $(obj).attr('data-type'),
				id = $(obj).closest('tr').attr('data-id'),
				$detailTr = $('#detail_' + id),
				$child = $detailTr.children(),
				$loading = $('#loading'),
				warehouseName = $('#warehouseName').attr('data-name');

			if (!id) {
				MYJ.message.error('获取产品id失败，请刷新页面后重试');
				return;
			}
			if (!+dataType) {
				$loading.modal('show');
				MYJ.ajax({
					type: 'GET',
					url: 'dxmCommodityProduct/showStockDetail.json?id=' + id,
					dataType: 'json',
					success: function (data) {
						$loading.modal('hide');
						if (!+data.code) {
							$child.html(INVENTORY_DETAIL_FN.inventoryDetailTable(data.data, warehouseName));
						} else {
							var str = '<div class="f-center lh34 m-bottom15">' + data.msg + '</div>';
							if (data.msg.indexOf() !== -1) {
								str = INVENTORY_DETAIL_FN.inventoryDetailTable([], warehouseName)
							}
							$child.html(str);
						}

						$detailTr.removeClass('hide');
					},
					error: function () {
						$loading.modal('hide');
					}
				})
			} else {
				$detailTr.addClass('hide');
			}
			$(obj).attr('data-type', !+dataType ? 1 : 0);
		},

		//生成仓库表格内容
		inventoryDetailTable: function (data, defaultWarehouse) {
			var templateTr = $('#inventoryDetaiTr').html(),
				tableStr = '';

			$.each(data, function (i, v) {
				if (i !== (data.length - 1) && defaultWarehouse !== v.warehouseName) {//去掉默认仓库的内容
					tableStr += templateTr.format({
						warehouseName: v.warehouseName || '0',
						onPassageNum: v.onPassageNum || '0',
						lockNum: v.lockNum || '0',
						availableStockNum: v.availableStockNum || '0',
						stockNum: v.stockNum || '0'
					})
				}
			});

			if (!tableStr) tableStr += '<tr><td colspan="5" class="f-center lh34 m-bottom15">暂无数据</td></tr>';
			return $('#inventoryDetailTable').html().format({
				allStr: tableStr
			});
		}
	};

})(jQuery, document, window);

//批量拆分订单弹层方法
var BATCH_SPLITED_ORDER = (function ($, D, W) {
	var commData = {
		local: gitWinLocHref()
	};


	//提示信息公用方法
	var commMsgFn = function (msg, type) {
		$.fn.message({type: type ? 'success' : 'error', msg: msg});
	};

	//ajax请求公用方法
	var commAjax = function(url, ajaxData, dataType, successCall, errCall, type){
		var $loading = $('#loading');

		$.ajax({
			type: type ? type : 'POST',
			url: commData.local + url,
			data: ajaxData,
			dataType: dataType,
			success: function (data) {
				$loading.modal('hide');
				successCall && typeof successCall === 'function' && successCall(data);
			},
			error: function () {
				$loading.modal('hide');
				if (errCall && typeof errCall === 'function'){
					errCall();
				}else{
					commMsgFn('网络异常，请稍后重试！');
				}
			}
		});
	};

	return {
		init: function () {
		    var that = this;

			$('#splitOrderDetailModal').find('.modal-dialog').addClass('w900');
			//添加包裹事件方法
			$(D).off('click', '#addPackageBtn').on('click', '#addPackageBtn', function () {
				if ($(this).hasClass('no-drop')) return;//如果禁用点击，则结束程序
				var $modalBody = $('#batchSplitedOrderModalBody'),
					isShopee = $modalBody.attr('data-platform') === 'shopee',
                    $theadTr = $modalBody.find('tr.theadTr'),
                    $tbodyTr = $modalBody.find('.splitedOrderTbody > tr'),
                    $lastTh = $modalBody.find('th.thPackage').last(),
					lastIndex = $lastTh.attr('data-index'),
					nextIndex = +lastIndex + 1,
					packageNumValidateStr = isShopee ? 'BATCH_SPLITED_ORDER.shopeePackageNumValidate(this);' : 'BATCH_SPLITED_ORDER.packageNumValidate(this);',
					packageThHtml = '<th class="w80 thPackage th-package f-center p-left10 p-right10" data-index="' + nextIndex + '"><span class="inline-block w-full f-center">包裹' + nextIndex + '</span><span class="iconfont icon_close f12-imp absolute pointer del-package delPackage"></span></th>',
					packageTdHtml = '<td class="w80 tdPackage td-package f-center p-left10 p-right10" data-index="' + nextIndex + '"><input type="text" class="form-component" value="0" oninput="' + packageNumValidateStr + '"/></td>',
					packageSumShowHtml = '<span class="inline-block packageSumShow f-center f13" data-index="' + nextIndex + '">&{sumText}</span>',
					tdAppendStr = '';

				if (isShopee && nextIndex > 5) {
					commMsgFn('Shopee平台一个订单最多可拆分5个包裹');
					return;
				}

				//添加包裹前先做下验证，如果有拆分的包裹数都是0，就不然它再继续添加
                if (that.validatePackageNum(lastIndex)) {
                    $tbodyTr.find('.tdPackage[data-index="' + lastIndex + '"] input').focus().select();
                    commMsgFn('包裹' + lastIndex + '的包裹数不能都是0');
                    return;
                }
                //验证所有商品是否都拆分完了，如果是，无需再继续添加，但如果至少还有一个商品可以再继续拆分，则可以继续添加包裹
				if (that.validateIsAddPackage()) {
					commMsgFn('请修改包裹数后再添加包裹');
					return;
				}

				$theadTr.append(packageThHtml);
                $tbodyTr.each(function (i, j) {
                	var isNoWeight = $(j).attr('data-weight') === '';//重量是否没有，如果没有重量信息，则总重量那列信息用--显示
					tdAppendStr = packageTdHtml;

					$(this).append(tdAppendStr);

					if (!+i) {
						//总数量增加处理
						$('#subShowDiv').find('.sumShow').each(function () {
							var sumShowStr = '',
								type = +($(this).attr('data-type'));

							if (type === 1) {
								sumShowStr = packageSumShowHtml.format({
									sumText: isNoWeight ? '--' : '0g'
								});
							} else {//商品种类/总数量
								sumShowStr = packageSumShowHtml.format({
									sumText: '0/0'
								});
							}
							$(this).append(sumShowStr);
						});
					}

				});
				that.initHanlde();//注册事件
				that.sumShowHandle();
				$('#scrollDiv').scrollLeft( $('#scrollDiv')[0].scrollWidth);//自动滚动到最右侧
			});
		},

		initHanlde: function() {
			var $deleteCloseBtn = $('#deleteCloseBtn'),
				that = this;

			$('.th-package,.td-package').mouseenter(function (e) {
				var index = $(this).attr('data-index'),
					$thPackage = $('.thPackage[data-index="' + index +'"]')/*,
					top = $thPackage.position().top,
					left = $thPackage.position().left,
					width = $thPackage.width()*/;

				// $deleteCloseBtn.removeClass('hide').css({left: (+left + width - 10) + 'px', top: (top) + 'px'});
				$thPackage.addClass('active');
				$('.td-package[data-index="' + index + '"]').addClass('active');
			}).mouseleave(function (e) {
				// #deleteCloseBtn
				// $deleteCloseBtn.addClass('hide');
				$('.th-package.active,.td-package.active').removeClass('active');
			});
			$(D).off('click', '.delPackage').on('click', '.delPackage', function () {
				if (!$(this).closest('.thPackage').hasClass('active')) return;
				var $activeTh = $(this).closest('.thPackage'),
					delIndex = +($activeTh.attr('data-index')),//当前要删除的那列下标
					lastIndex = $('.thPackage').last().attr('data-index'),
					// $delSumShowPackage = $('.packageSumShow[data-index="' + delIndex + '"]'),
					isLast = true;

				//处理表头
				if (lastIndex > delIndex) {//如果删除的这列不是最后的那列，则需要将后面的下标顺序调前一位
					$('.thPackage:gt(' + (delIndex - 1) + ')').each(function () {
						var currentIndex = $(this).attr('data-index'),
							newIndex = currentIndex - 1,
							packThStr = '<span class="inline-block w-full f-center">包裹' + newIndex + '</span>' +
								'<span class="iconfont icon_close f12-imp absolute pointer del-package delPackage"></span>';

						$(this).attr('data-index', newIndex).html(packThStr);
					});
					isLast = false;
				}
				$activeTh.remove();


				//处理表体，需要重新计算数量
				$('tr.productTr').each(function () {
					var $this = $(this),
						$firstTd = $this.find('.tdPackage').first(),
						firstPackNum = $.trim($firstTd.text()),
						$delTd = $this.find('.tdPackage[data-index="' + delIndex + '"]'),
						val = +($delTd.find('input').val());

					$firstTd.text(+firstPackNum + val);//包裹1加上删除这列的包裹数
					//如果删除的这列不在最后面，则后面的包裹索引自动前进一个
					if (!isLast) {
						$this.find('.tdPackage:gt(' + (delIndex - 1) + ')').each(function () {
							var currentIndex = $(this).attr('data-index'),
								newIndex = currentIndex - 1;

							$(this).attr('data-index', newIndex);
						});
					}
					$delTd.remove();
				});

				$('.sumShow').each(function () {
					var $this = $(this),
						$delSpan = $this.find('.packageSumShow[data-index="' + delIndex + '"]');

					//如果删除的这列不在最后面，则后面的总重量显示那里的索引自动前进一个
					if (!isLast) {
						$this.find('.packageSumShow:gt(' + delIndex + ')').each(function () {
							var currentIndex = $(this).attr('data-index'),
								newIndex = currentIndex - 1;

							$(this).attr('data-index', newIndex);
						});
					}
					$delSpan.remove();
				});
				that.sumShowHandle();
				BATCH_SPLITED_ORDER.calculationResultShow();
			});
		},

		//点击显示拆分弹层时，处理下样式
		modalShowHandle: function(platform) {
			$('#batchSplitedOrderModalBody').attr('data-platform', platform ? platform : '');
			this.sumShowHandle();
		},

		//总重量显示样式控制
		sumShowHandle: function() {
			var $thPackage = $('th.thPackage');

			//总重量显示位置控制
			$thPackage.each(function (i, j) {
				var index = $(this).attr('data-index'),
					newWidth = $(this).width() + 21,
					$packageSumShow = $('.packageSumShow[data-index="' + (+index) + '"]');

				if (!i) {
					var left = $('.theadTr th:nth-child(1)').width() + $('.theadTr th:nth-child(2)').width();

					$('.packageSumShow[data-index="-1"]').css('width', (left + 21) + 'px');

					$('.packageSumShow[data-index="0"]').css('width', ($('th.totalNumTh').width() + 1) + 'px');
				}

				// if (index > 1) newWidth += 20;//加上左右内边距

				$packageSumShow.css('width', newWidth + 'px');
			});
		},

		//拆分包裹数量输入框输入计算处理
		packageNumValidate: function(obj) {
			clearMistakeNumber(obj);//非数字矫正
			var $tr = $(obj).closest('tr.productTr'),
				packageTotalNum = +($tr.attr('data-packnum')),//总包裹数
				$firstPack = $tr.find('td.tdPackage').first(),//包裹1
				firstPackNum = $.trim($firstPack.text()),
				$td = $(obj).closest('td'),
				currentNum = +($(obj).val()),
				$otherPackTd = $td.siblings('td.tdPackage[data-index!=1]'),//其他包裹列，不包含包裹1
				otherNum = 0,
                packageOneNum = 0;//包裹1总个数 如果只剩一个的时候

			//加上其他包裹的数量
			if ($otherPackTd.length) {
				$otherPackTd.each(function () {
					var num = +($(this).find('input').val());

					otherNum += num ? num : 0;
				});
			}

			currentNum = currentNum ? currentNum : 0;
			//总包裹数减去其他包裹数,剩下的数量将当前包裹数和包裹1数进行分配，
			// 但包裹1不能小于或者等于0，所以要对当前修改的包裹数做输入范围的限制
			var newPackNum = packageTotalNum - otherNum;

			// if (newPackNum > 1) {
				firstPackNum = newPackNum - currentNum;//剩下的包裹分配包裹1和当前包裹数

				if (firstPackNum < 0) {//第一个包裹数量被减到负数，则第一个包裹数量保留0，并重新分配当前输入的包裹数
					firstPackNum = 0;
					currentNum = newPackNum - firstPackNum;
					$(obj).val(currentNum);
				}
			// }
			$firstPack.text(firstPackNum);//可以正常修改的时候，只改第一个包裹数量
            $('td[data-index="1"]').each(function () {
                var packOne = +($(this).text());

                packageOneNum += packOne;
            });
            if (packageOneNum < 1) {
                $firstPack.text(1);
                $(obj).val(currentNum - 1 < 0 ? 0 : currentNum - 1);
            }
            BATCH_SPLITED_ORDER.calculationResultShow();
		},

		//Shopee平台拆分包裹数量输入框输入计算处理（因为Shopee平台的校验比较特殊，需要单独拆开来写）
		shopeePackageNumValidate: function(obj) {
			clearMistakeNumber(obj);//非数字矫正
			var $tr = $(obj).closest('tr.productTr'),
				packageTotalNum = +($tr.attr('data-packnum')),//总包裹数
				$firstPack = $tr.find('td.tdPackage').first(),//包裹1
				$td = $(obj).closest('td'),
				currentNum = +($(obj).val()),
				$otherPackTd = $td.siblings('td.tdPackage'),//其他包裹列
				firstPackageNum = 0;

			// 如果填写的数量不等于产品总数或不等于0，则将填写数量自动填写为产品总数
			if (currentNum <= 0) {
				currentNum = 0;
				firstPackageNum = packageTotalNum;
			} else {
				if (currentNum !== packageTotalNum) commonMsgFn('Shopee接口不支持按数量拆分，包裹内产品的数量须和产品的总数相同');
				currentNum = packageTotalNum;
				firstPackageNum = 0;
			}
			$(obj).val(currentNum);

			//加上其他包裹的数量
			if ($otherPackTd.length) {
				$otherPackTd.filter('[data-index=1]').text(firstPackageNum);
				$otherPackTd.filter('[data-index!=1]').find('input').val(0);//其他包裹列，不包含包裹1
			}
			BATCH_SPLITED_ORDER.calculationResultShow();
		},

        //计算结果显示处理
        calculationResultShow: function() {
		    var obj = {};

            $('tr.productTr').each(function (i, j) {
                var weight = +($(j).attr('data-weight'));//单个包裹重量

                weight = weight ? weight : 0;
                $(this).find('.tdPackage').each(function (a, b) {
                    var index = $(b).attr('data-index'),
                        isFirstPack = +index === 1,//是否为包裹1
                        packNum = isFirstPack ? $(b).text() : $(b).find('input').val();

                    packNum = +packNum ? +packNum : 0;

                    if (!obj.hasOwnProperty(index)) {
                        obj[index] = {
                            packWeight: +((packNum * weight).toFixed(2)),//包裹重量(计算总重量使用)
                            skuNum: packNum ? 1 : 0,      //商品种类，大于0才算有该种的商品种类（计算商品种类使用）
                            packNum: packNum             //包裹数（计算总数量使用）
                        }
                    } else {
                        var oldPackageWeight = obj[index].packWeight ? obj[index].packWeight : 0,
                            oldSkuNum =  obj[index].skuNum ? obj[index].skuNum : 0,
                            oldPackNum =  obj[index].packNum ? obj[index].packNum : 0,
							packTotalWeight = +((packNum * weight).toFixed(2));

                        obj[index].packWeight = +((+oldPackageWeight + packTotalWeight).toFixed(2));
                        obj[index].skuNum = +oldSkuNum + (packNum ? 1 : 0);
                        obj[index].packNum = +oldPackNum + packNum;
                    }
                });
            });

            if (!isEmptyObject(obj)) {
            	var totalWeightIsEmpty = $.trim($('.sumShow').first().find('span[data-index="0"]').text()) === '--';
                $.each(obj, function (index, info) {
                    index = +index;
                    var $sumShow = $('.sumShow'),
                        $totalSumShow = $sumShow.eq(0).find('.packageSumShow[data-index="' + index + '"]'),
                        $singleSumShow = $sumShow.eq(1).find('.packageSumShow[data-index="' + index + '"]');

                    if ($totalSumShow.length) $totalSumShow.text((info.packWeight ? info.packWeight + 'g' : (totalWeightIsEmpty ? '--' : '0g')));
                    if ($singleSumShow.length) $singleSumShow.text(info.skuNum + '/' + info.packNum);
                });
            }
            obj = null;//释放内存
        },

		//验证指定列的包裹数量
		validatePackageNum: function(column) {
			var $td = $('td.tdPackage[data-index="' + column + '"]'),
				isStop = true;//验证这个包裹的这一列是不是都是0，如果是的话，就要报错

			if ($td.length) {
				$td.each(function () {
					var num = $(this).find('input').val();

					if (+num) {
						isStop = false;
						return false;//如果有填了大于0的数，则不再需要验证，直接跳出循环
					}
				});
				return isStop;
			} else {
				return false;
			}
		},

		//验证是否可以继续添加包裹，检测下包裹是否已经拆分完了，如果是，则不需要再加包裹拆分，但只要还有sku的包裹没完全拆分完，就可以继续加
		validateIsAddPackage: function() {
			var $productTr = $('.splitedOrderTbody > tr.productTr'),
				len = $productTr.length,
				hasSplitedNum = 0;//如果包裹拆到最小单位1了，则说明后面无需再做拆分，当所有的商品包裹数都是1的时候，则拆到最小值，则不能再添加包裹

			if (len) {
				$productTr.each(function (i, j) {
					var totalPackNum = $(j).attr('data-packnum'),
						onlyOnePackNum = 0,//只有一个包裹的数量
						$tdPackage = $(j).find('.tdPackage'),
						packNum = $tdPackage.length;

					$tdPackage.each(function (m, n) {
						var num = !+m ? +($(n).text()) : +($(n).find('input').val());
						num = num ? +num : 0;

						if (+num === 1) onlyOnePackNum++;

						if (m === packNum && onlyOnePackNum === packNum) hasSplitedNum++;//记录已拆分完的数量
					});
				});
			}
			return len === hasSplitedNum;//添加包裹，检测下包裹是否已经拆分完了，不需要再加包裹拆分
		},

		//批量拆分订单提交(目前只支持eBay平台)
		batchSplitOrderSubmit: function() {
			var that = this,
				$modal = $('#splitOrderDetailModal'),
				$tbody = $modal.find('tbody.splitedOrderTbody'),
				$productTr = $tbody.find('.productTr'),
				// orderNums = [],
				ajaxData = {
					packageId: $modal.find('input[name="packageId"]').val()
				},
				flag = false,
				splitedPackNum = $modal.find('.theadTr > th.thPackage').length;//拆分的包裹数

			if ($productTr.length) {
				var splitOrderList = [];
				/*[
					[{sku:a,num:1},{sku:b,num:2}],
					[{sku:a,num:1},{sku:b,num:1}],
					[{sku:a,num:1},{sku:b,num:0}]
				]*/
				for (var a = 0; a < splitedPackNum; a++) {
					//从包裹2开始验证每列的包裹数是否都是0，如果是则拦截报错
					if (a) {
						flag = that.validatePackageNum(a+1);
						if (flag) {
							commMsgFn('包裹' + (+a+1) + '的包裹数不能都是0');
							return;//报错并终止循环
						}
					}

					var packList = [];//[{sku:a,num:1},{sku:b,num:2},{},{},{}]

					$productTr.each(function (i, j) {
						var $this = $(j),
							sku = $this.attr('data-sku'),
							$tdPackage = $this.find('td.tdPackage').eq(a),//找到所属sku所对应那列的包裹
							isFirstPackage = +($tdPackage.attr('data-index')) === 1,
							num = isFirstPackage ? $.trim($tdPackage.text()): $tdPackage.find('input').val();


						packList.push({
							sku: sku,
							num: +num ? num : '0'
						});
					});
					if (!flag && packList.length) splitOrderList.push(packList);
				}
			}
			if (flag || !splitOrderList.length) return;
			ajaxData.splitOrderList = JSON.stringify(splitOrderList);
			commAjax('order/batchSplitOrder.json', ajaxData, 'json', function (data) {
				if (!+data.code) {
					commMsgFn('操作成功，订单拆分成功', 1);
					$('#packageDetailModal').modal('hide');
					$modal.modal('hide').find('.modal-dialog').removeClass('w900');//关闭弹层时移除设置的宽度;
					refreshAjaxPage();
				} else {
					commMsgFn(data.msg ? data.msg : '订单拆分失败');
					$modal.modal('hide').modal('show');
				}
			});
		},

		//批量拆分弹层关闭
		closeDiv: function (id) {
			closeDiv(id);
			$('#' + id).find('.modal-dialog').removeClass('w900');//关闭弹层时移除设置的宽度
		},

		//打开批量追加商品
		openBatchAddOnItem: function () {
			var packageIds = getCheckBoxValByName('packageId');
			if (packageIds === '') {
				$.fn.message({type: 'error', msg: '请至少选择一个订单'});
				return;
			}

			MYJ.ajax({
				url: 'package/checkYcPackageState.json',
				data: {
					ids: packageIds
				},
				success: function (res) {
					if (!+res.code) {
						$('#batchAddItemCloudId').modal('show');
						BATCH_SPLITED_ORDER.addProductMethod();
						$('#warehouseTitleNameId').text(res.warehouseName);
						var notTr = $('#notEmptyTrContentId').html()
						$('#batchCloudTbodyId').empty().html(notTr);
						BATCH_SPLITED_ORDER.openLookActiveMethod();
						$('#recodeParcelId').val(packageIds); //记录包裹id
						BATCH_SPLITED_ORDER.initFormEventMethod(); //form表单校验
					} else {
						var $purchaseTipErrorModalId = $('#purchaseTipErrorModalId');
						$purchaseTipErrorModalId.find('#errorMsgId').html(res.msg);
						$purchaseTipErrorModalId.modal('show');
					}
				}
			});
		},

		//打开商品弹层
		openLookActiveMethod: function () {
			//阻止事件冒泡和默认值
			var event = window.event;
			event.stopPropagation();
			event.preventDefault();

			$('#searchProposalBatchSelectType').val('1');
			$('#searchProposalSelectValue').val('');
			$('#itemSkuStateId').addClass('tab-active').siblings().removeClass('tab-active');
			$('#selProBatchOrder').empty();
			BATCH_SPLITED_ORDER.batchOrderItemMethod();
			BATCH_SPLITED_ORDER.itemEchoLookMethod();
			$('#batchQuoteGoodsModal').customModal('show');
		},

		//商品回显
		itemEchoLookMethod: function () {
            var $contentTr =  $('#batchCloudTbodyId').find('tr.content'),
				selectProductOrderItemAdd = $('#selectProductOrderItemId').html(),
				$selSingleStrAdd = '';

            $.each($contentTr, function(){
				$selSingleStrAdd +=  selectProductOrderItemAdd.format({
					idStr: $(this).attr('data-id'),
					imgUrl: $(this).find('.imgCss').attr('src'),
					sku: $.trim($(this).find('.proSku').text()),
					name: $.trim($(this).find('.proName').text())
				});
			});

            $('#selProBatchOrder').html($selSingleStrAdd);
			$('#selProProposalNum').text($('#selProBatchOrder .purSelSingle').length);
		},

		//弹层批量商品
		batchOrderItemMethod: function () {
			MYJ.ajax({
				url: 'yuncangWarehouseSku/warehouseSkuList.htm',
				data: {
					isBatch: 1
				},
				success: function (res) {
					var $selectProposalBatchPageList = $('#selectProposalBatchPageList'),
						selectWareHoseProductsPageList = $('#selectWareHoseProductsPageList');
					$selectProposalBatchPageList.empty();
					selectWareHoseProductsPageList.empty();
					$selectProposalBatchPageList.html(res);
					BATCH_SPLITED_ORDER.recodeCheckedItemIdMethod();
				}
			});
		},

		//注册添加产品交互
		addProductMethod: function () {
			$(document).off('click', '#selProBatchOrder .purSelDelBtn').on('click', '#selProBatchOrder .purSelDelBtn', function () {
				var liId = $(this).closest('.purSelSingle').attr('id').split('_')[1];
				$('#ida_' + liId).html('<span>选择</span>');
				$('.headTabPane[id="alreadyGhsProProduct"]').find('#ida_' + liId).html('<span>选择</span>');
				BATCH_SPLITED_ORDER.delSelectTrProposal(liId);
			});


			$(document).off('click', '.purSelBox .purSelDelAllBtn').on('click', '.purSelBox .purSelDelAllBtn', function () {
				var $purSelSingle = $(this).closest('.purSelBox').find('.purSelSingle'),
					liId = '';
				if ($purSelSingle.length) {
					$.each($purSelSingle, function (i, j) {
						liId = $(j).attr('id').split('_')[1];
						$('#ida_' + liId).html('<span>选择</span>');
						$('.headTabPane[id="alreadyGhsProProduct"]').find('#ida_' + liId).html('<span>选择</span>');
						BATCH_SPLITED_ORDER.delSelectTrProposal(liId);
					});
				}
			});
		},

		//选中商品
		selectProProposal: function (id, obj) {
			var $selProBatchOrder = $('#selProBatchOrder'),
				selectProductOrderItemAdd = $('#selectProductOrderItemId').html();

			if ($selProBatchOrder.find('#selectProductLi_' + id).attr('id')) {
				$(obj).html('<span>选择</span>');
				BATCH_SPLITED_ORDER.delSelectTrProposal(id);
			} else {
				$(obj).html('<span class="f-green">已选择</span>');
				var imgUrl = $('#hiddenMainImagez_' + id).val(),
					data = {
						idStr: id,
						imgUrl: imgUrl === '' ? 'static/img/kong.png' : imgUrl,
						sku: $('#hiddenSkuz_' + id).val(),
						name: $('#hiddenNamez_' + id).val()
					},
					$selSingleStrAdd = $(selectProductOrderItemAdd.format(data));

				$selProBatchOrder.append($selSingleStrAdd);
				// 添加产品数量处理
				$('#selProProposalNum').html($selProBatchOrder.find('.purSelSingle').length);
			}
		},

		//移除已选择
		delSelectTrProposal: function (id) {
			var $selLi = $('#batchQuoteGoodsModal').find('#selProBatchOrder #selectProductLi_' + id),
				idLength = 0;
			$selLi.remove();
			idLength = $('#selProBatchOrder .purSelSingle').length;
			$('#selProProposalNum').html(idLength);
		},

		//记录选中商品id
		recodeCheckedItemIdMethod: function () {
			var $divObj = $('#selProBatchOrder').find('.purSelSingle'),
				$productContentTbody = $('#SkusContent'),
				currentId;

			$divObj.each(function () {
				currentId = $(this).attr('data-id');
				$productContentTbody.find('tr.content').find('#ida_' + currentId).html('<span class="fGreen">已选择</span>')
			});
		},

		//确认选择
		deterSelectMethod: function () {
            var $purSelSingle = $('#selProBatchOrder .purSelSingle'),
				purLength = $purSelSingle.length,
				itemTrOrder = $('#itemTrOrderId').html(),
			    orderTr = '', currentId = '',
			    $batchCloudTbodyId = $('#batchCloudTbodyId'), checkLength = 0;

			if (!purLength) {
				$.fn.message({type: 'error', msg: '请至少选择一个商品'});
				return;
			}

            $.each($purSelSingle, function(){
				//判断当前商品是否存在
				currentId = $(this).attr('data-id');
				checkLength = 0;
				checkLength = $batchCloudTbodyId.find('tr[data-id="' + currentId + '"]').length;
				if (!checkLength) {
					orderTr += itemTrOrder.format({
						imgUrl: $(this).find('img').attr('src'),
						idStr: $(this).attr('data-id'),
						sku: $.trim($(this).find('.proSku').text()),
						name: $.trim($(this).find('.proName').text())
					})
				}
			});
			$batchCloudTbodyId.find('.noDataTrBox').remove();
			$batchCloudTbodyId.append(orderTr);
			$('#batchQuoteGoodsModal').customModal('hide');
		},

		//移除商品
		removeItemMethod: function (obj) {
			$(obj).closest('tr').remove();

			var productLength = $('#batchCloudTbodyId').find('tr.content').length,
				notTr = $('#notEmptyTrContentId').html();

			if (!productLength) {
				$('#batchCloudTbodyId').html(notTr);
			}
		},

		//注册表单事件
		initFormEventMethod: function () {
			$('form#batchAddItemFormId').Validform({
				btnSubmit: '.toSubmit',
				showAllError: true,
				tipSweep: false,
				ignoreHidden: true, // 是否对隐藏表单验证
				datatype: {
                  skuNum: function (objVal){
                  	if(!+objVal){
                  		return '请填写商品数量';
					}else{
                  		if(+objVal > 999999){
                  			return '商品数量最多添加999999';
						}
					}
				  }
				},
				tiptype: function (msg, o) {
					//msg：提示信息;
					//o:{obj:*,type:*,curform:*}, obj指向的是当前验证的表单元素（或表单对象），type指示提示的状态，值为1、2、3、4， 1：正在检测/提交数据，2：通过验证，3：验证失败，4：提示ignore状态, curform为当前form对象;
					//cssctl:内置的提示信息样式控制函数，该函数需传入两个参数：显示提示信息的对象 和 当前提示的状态（既形参o中的type）;
					if (!o.obj.is('form')) {//验证表单元素时o.obj为该表单元素，全部验证通过提交表单时o.obj为该表单对象;
						var td = o.obj.closest('.validformOut');
						if (td.find('.errorMsg').length) $('<div></div>').append(td.find('.errorMsg')).empty();
						var $errorMsg = $('<div class="f-red f12 errorMsg"><span class="errorMsgContent"></span></div>');
						if (+o.type === 3) {
							td.append($errorMsg);
							$errorMsg.find('.errorMsgContent').text(msg);
						}
					}
				},
				beforeSubmit: function (curform) {
					BATCH_SPLITED_ORDER.orderDeterMethod();
					return false;
				}
			});
		},

		//关闭全屏弹层判断是否有数据，有则直接关闭
		closeMoreGreenMethod: function () {
			var productLength = $('#batchCloudTbodyId').find('tr.content').length;
			if (!productLength) $('#batchAddItemCloudId').modal('hide');
		},

		//确认保存
		orderDeterMethod: function () {
			var $trContent = $('#batchCloudTbodyId').find('tr.content'),
				productLength = $trContent.length, productList = [];

			if(!productLength){
				$.fn.message({type: 'error', msg: '请最少添加一个商品！'});
				return ;
			}

			$.each($trContent, function() {
				productList.push({
					originCount: 0,
					goodsId: $(this).attr('data-id'),
					goodsCount: $.trim($(this).find('.skuAllNum').val())
				})
			});
			var vo = {
				productList: productList,
				dxmOrderIds: $('#recodeParcelId').val()
			};

		  	MYJ.ajax({
			  	url: 'package/batchAddYcProduct.json',
			  	data: JSON.stringify(vo),
				dataType: 'json',
				contentType: 'application/json',
			  	success: function (res) {
					if(!res.code){
						$.fn.message({type: 'success', msg: '追加成功'});
						$('#batchAddItemCloudId').modal('hide');
						 refreshAjaxPage('package'); //刷新页面
					}else{
						$.fn.message({type: 'error', msg: res.msg});
					}
			  	}
		  	});

		}
	};
})(jQuery, document, window);

$(document).off('blur', '.batchPackInfoEmails').on('blur', '.batchPackInfoEmails', function () {
    var $this = $(this),
        buyerEmail = $.trim($this.val()),
        validateEmail = /^([a-zA-Z0-9]|[\_|\.|\-])+@([a-zA-Z0-9]|[\_|\.|\-])*\.[a-zA-Z0-9]+$/,
        $detailEmail1 = $this.closest('[role="detailEmail1"]');

    $this.removeClass('border-red');
    $detailEmail1.find('.detailEmailErrorMsg').remove();
    if(buyerEmail && !buyerEmail.match(validateEmail)){
        $this.addClass('border-red');
        $detailEmail1.append('<div class="f-red detailEmailErrorMsg">邮箱格式不正确</div>');
    }
});

// 自定义表头选择相关方法
var excelHeaderFields = [], // 店小秘手工单Excel表头字段
    excelHFieldsInnerList = {}, // 二级分类列表
    excelFielsKeysInfo = {}, // 手工订单字段key 详情集合
	isFirsInit = true, // 第一次加载选择字段弹窗
    EXCEL_FIELDS_FN = (function ($, D, W) {

    //分类弹层类目项点击事件
    $(D).off('click', '.categoryDiv').on('click', '.categoryDiv', function () {
        EXCEL_FIELDS_FN.categoryClickFn(this);
    });

    //分类弹层确认按钮事件
    $(D).off('click', '.selectCategory').on('click', '.selectCategory', function () {
        EXCEL_FIELDS_FN.categoryModalConfirmFn();
    });
    return {
    	// 点击下拉字段下拉框 - 打开选字段弹层
		showExelField: function(obj) {
			var that = this,
				$obj = $(obj),
				$customExcelFieldModal = $('#customExcelFieldModal'),
				fieldKey = $obj.attr('data-key') || 'noNeedTranFlag',
				mustFlag = $obj.attr('data-mustFlag'),
				 parentKey = $obj.attr('data-parentKdy'),
				 curKeyIndex = $obj.attr('data-keyIndex'),
				 curValue = $obj.attr('data-value'),
				colum = $obj.closest('td').attr('data-colum'),
				firstFieldList = excelHeaderFields; // 默认手工订单一级列表
			if(fieldKey !== 'noNeedTranFlag'){
				// 非不导入的字段 - 还原到列表
				var curObj = {
					innerList: '',
					key: fieldKey,
					mustFlag: mustFlag,
					value: curValue
				},
				hasKey = false;
				if (parentKey) {
					var childList = excelHFieldsInnerList[parentKey]; // 默认手工订单二级列表
					$.each(childList, function (i, j) {
						var keys = j.key;
						if (keys === fieldKey) {
							hasKey = true;
							return;
						}
					})
					if (!hasKey) childList.unshift(curObj);
				} else {
					$.each(firstFieldList, function (i, j) {
						var keys = j.key;
						if (keys === fieldKey) {
							hasKey = true;
							return;
						}
					})
					if (!hasKey) firstFieldList.splice(1, 0, curObj);
				}
			}
			that.categoryShow(firstFieldList);
			// 选中当前选项
			if (parentKey) {
				$('.categoryChooseMiddleDiv span[fieldkey="' + parentKey + '"]').click();
			}
			$('.categoryChooseMiddleDiv span[fieldkey="' + fieldKey + '"]').closest('.categoryDiv').addClass('bgColor5 selectCategoryId');
			$customExcelFieldModal.attr('data-colum', colum).modal('show');
		},
        // 获取自定义报个所需的表头数据
        getCustomExcelFields: function(templateId) {
            var that = this;
            MYJ.ajax({
                url: 'excel/getParam.json',
                pointKey: 'getParam',
                data: {
                    type: 'order'
                },
                success: function(res) {
                    if(!+res.code) {
						isFirsInit = true;
                        excelHeaderFields = res.data || [];
						// 处理选择字段弹窗数据
						that.categoryShow(excelHeaderFields);
                        // 切换模板处理表格字段
                        if (!!templateId) {
							EXPORT_CUSTOM_EXCEL_FN.changeExcelTemplate(templateId);
						}
                    }
                }
            })
        },
        // 字段弹层处理
        categoryShow: function (arr, obj) {
            var str = this.categoryHtml(arr);

            if (!obj) {
                var $categoryChooseInDiv = $('#customExcelFieldModal').find('div.categoryChooseInDiv');

                $categoryChooseInDiv.hide().find('div.categoryList').empty();
                $categoryChooseInDiv.find('div.serch input').val('');
                $categoryChooseInDiv.first().show().find('div.categoryList').html(str);
                $('.categoryChooseCrumbs').find('span').each(function () {
                    if (+$(this).attr('data-level') !== 1) {
                        $(this).empty();
                    } else {
                        $(this).html('未选择字段');
                    }
                });
            } else {
                var $obj = $(obj).next();
                $obj.find('div.categoryList').empty();
                $obj.find('div.serch input').val('');
                $obj.nextAll().hide().find('div.categoryList').empty();
                $obj.nextAll().find('div.serch input').val('');
                $obj.show().find('div.categoryList').html(str);
            }
        },
        //分类弹层类目html生成
        categoryHtml: function (arr) {
            var str = '';
            $.each(arr, function (i, j) {
                var fieldName = j.value,
                    fieldKey = j.key,
					parentKey = j.parentKey || '',
                    innerList = j.innerList || [];
                excelFielsKeysInfo[fieldKey] = j;
                str += '<div class="categoryDiv"><span class="categoryNames" fieldKey="' + fieldKey + '"' +
                    ' title="' + fieldName + '" data-childLen="' + innerList.length + '" data-parentKdy="' + parentKey + '" data-keyIndex="' + i + '">' + fieldName + '</span>';
                if (!!innerList && innerList.length) {
                	if (isFirsInit) {
						excelHFieldsInnerList[j.key] = j.innerList; // 默认手工订单二级列表
						$.each(j.innerList, function (ii, itemI) {
							itemI.parentKey = fieldKey;
							excelFielsKeysInfo[itemI.key] = itemI;
						})
						isFirsInit = false;
					}
                    str += '<span class="glyphicon glyphicon-chevron-right" data-isleaf="0"></span></div>';
                } else {
                    str += '<span class="glyphicon glyphicon-chevron-right" data-isleaf="1" style="display:none;"></span></div>';
                }
            });
            return str;
        },
        //分类弹层类目选项点击事件
        categoryClickFn: function (obj, call) {
            var that = this,
                shopId = $('#shopId').val(),
                $that = $(obj),
                isleaf = $that.find('span.glyphicon').attr('data-isleaf'),
                $obj = $that.closest('div.categoryChooseInDiv'),
                names = $that.find('span.categoryNames').attr('title'),
                fieldKey = $that.find('span.categoryNames').attr('fieldKey'),
                level = $obj.attr('data-level'),
                str = '<span id="' + fieldKey + '">' + (+level === 1 ? '' : '&nbsp;>&nbsp;') + names + '</span>';

            //添加背景色
            $that.closest('div.categoryChooseInDiv').find('.categoryDiv').removeClass('bgColor5');
            $that.addClass('bgColor5');

            //判断有没子集
            if (+isleaf === 0) { //等于0说明还有子级分类
                $('.selectCategoryId').removeClass('selectCategoryId');
                $that.addClass('selectCategoryId');

				var childList = excelHFieldsInnerList[fieldKey]; // 默认手工订单二级列表
                that.categoryShow(childList, $obj);
                //生成路径
                $('.categoryChooseCrumbs').find('span[data-level="' + level + '"]').html(str).nextAll().empty();
                call && typeof call === 'function' && call();
            } else { //等于1则没有子级分类
                $('.selectCategoryId').removeClass('selectCategoryId');
                $that.addClass('selectCategoryId');
                $obj.nextAll().hide().find('div.categoryList').empty();
                //生成路径
                $('.categoryChooseCrumbs').find('span[data-level="' + level + '"]').html(str).nextAll().empty();
                call && typeof call === 'function' && call();
            }
        },
        //选择分类弹层确认事件
        categoryModalConfirmFn: function (isCloseBtn) {
            var that = this,
				colum = $('#customExcelFieldModal').attr('data-colum'),
				$curItem = $('.selectCategoryId .categoryNames'),
				childLen = $curItem.attr('data-childLen'),
				parentKey = $curItem.attr('data-parentKdy'),
				curKeyIndex = $curItem.attr('data-keyIndex') || '',
                fieldKey = $curItem.attr('fieldKey') || 'noNeedTranFlag', // 未选择默认 不导入

				$curSelect= $('.selectTr').find('td[data-colum="' + colum + '"] select'),
				oldparentKey = $curSelect.attr('data-parentkdy'),
				oldKeyIndex = $curSelect.attr('data-keyindex') || '',
				oldSelFieldKey = $curSelect.attr('data-key');
            if(!!isCloseBtn) {
            	// 取消/关闭弹窗 选择不生效
				fieldKey = 'noNeedTranFlag';
			}

			// 编辑后未选 关闭时默认用编辑前的
			if (oldSelFieldKey && (+childLen || !!isCloseBtn)) {
				fieldKey = oldSelFieldKey;
				childLen = 0;
				parentKey = oldparentKey;
				curKeyIndex = oldKeyIndex;
			}
            if (fieldKey !== 'noNeedTranFlag' && !+childLen) {
            	// 列表去除已选择选项
				var delIn = -1;
            	if (parentKey) {
                    // 手工订单二级列表
                    $.each(excelHFieldsInnerList[parentKey], function(i, j) {
                        if (j.key === fieldKey) {
                            delIn = i;
                            return;
                        }
                    })
                    if(delIn > -1) excelHFieldsInnerList[parentKey].splice(delIn, 1); // 选中模板
				} else {
                    $.each(excelHeaderFields, function(i, j) {
                        if (j.key === fieldKey) {
                            delIn = i;
                        }
                    })
                    if(delIn > -1) excelHeaderFields.splice(delIn, 1); // 手工订单一级列表
				}
			}
            // 将选项赋值到对应的列
			if (!+childLen) {
				var curValue = excelFielsKeysInfo[fieldKey].value,
					optionStr = '<option value="' + fieldKey +'" selected>' + curValue + '</option>';
				$curSelect.empty().attr({
					'data-mustFlag': excelFielsKeysInfo[fieldKey].mustFlag,
					'data-key': fieldKey,
					'data-parentKdy': parentKey,
					'data-keyIndex': curKeyIndex,
					'title': curValue,
					'data-value': curValue
				}).html(optionStr);
			}
            EXCEL_FIELDS_FN.totalColunNum();
            EXCEL_FIELDS_FN.closeBtn();
        },
		// 计算选择的字段数量
		totalColunNum: function() {
			var $td = $('.selectTr td'),
				total = 0;
			$.each($td, function(i, j) {
				var $select = $(this).find('select'),
					keys = $select.attr('data-key');
				if (keys && keys !== 'noNeedTranFlag') {
					total += 1;
				}
			})
			$('#choseColumn').empty().text(total);
		},
        closeBtn: function () {
            $('#customExcelFieldModal').modal('hide');
            $('#customExcelChangeTableModal').customModal('show');
        }
    }
})(jQuery, document, window);

// 识别表格 映射关系 相关方法
var curTemplateFieldsList = [], // 当前选中模板列表
	allTemplateIdsInfo = {}, // 全部模板列表集合
	EXPORT_CUSTOM_EXCEL_FN = (function ($, D, W) {
	// 导入订单 自定义文件选择确定事件
	$(D).off('change', '#customFileInput').on('change', '#customFileInput', function (e) {
		var fileType = e.currentTarget.files[0].type,
			fileName = e.currentTarget.files[0].name;
		if(!fileType || !/\.(?:xlsx|xls|xlsm)$/.test(fileName)) {
			$.fn.message({type: 'error', msg: '导入文件格式错误，仅支持EXCEL格式'});
			return;
		}
		EXPORT_CUSTOM_EXCEL_FN.getExcelData(e.currentTarget.files);
		EXPORT_CUSTOM_EXCEL_FN.getTemplateList(); // 模板列表
		EXCEL_FIELDS_FN.getCustomExcelFields(); // 重新获取分类

	});
	//对特殊字符进行特殊转义处理，防止在页面被截断
	var strReplace = function (name) {
		return name.replace(/\'/g, '$#39;').replace(/\"/g, '&quot;').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
	};
	//生成table表格
	var creatTable = function (excelData, tableContentDom) {
		var tableStartStr = '<table class="myj-table table-no-hover">',
			tableEndStr = '</table>',
			theadStartStr = '<thead><tr class="theadTr">',
			theadEndStr = '</tr></thead>',
			tbodyStartStr = '<tbody>',
			tbodyEndStr = '</tbody>',
			tableHtmlStr = tableStartStr,
			theadHtmlStr = theadStartStr + '<th class="f-center minW80 w80 headerTr p-top15 p-bottom15" data-column="1">标题行</th>',
			tbodyHtmlStr = tbodyStartStr,
			singleSelectHtmlStr = '<select class="form-control w130 minW130-imp p-left0 inline-block" data-oldvalue="不导入" title="不导入" onclick="EXCEL_FIELDS_FN.showExelField(this);"><option value="noNeedTranFlag">不导入</option></select>',
			selectHtmlStr = '<tr class="selectTr" data-row="1"><td class="f-center p-top10 p-bottom10" data-column="1">小秘字段名</td>',//生成每一列的下拉框节点
			excelDataTrHtmlStr = '',
			allColumn = 0;//总列数

		$.each(excelData, function (i, j) {//生成行
			if (!isEmptyObject(j)) {
				var row = i + 1,//做下标记，记住当前行
					column = 1;//做下标记，记住当前列

				excelDataTrHtmlStr += '<tr class="dataTr" data-row="'+ (row + 1) + '"><td class="f-center minW80 w80 p-top10 p-bottom10" data-column="1">' + row + '</td>';

				$.each(j, function (key, value) {//生成列
					var headName = $.trim(key),//表头标题
						bodyValue = value !== '&nbsp;' ? strReplace($.trim(value)) : $.trim(value),//body里面的内容
						isOverLen = bodyValue.length > 19;//内容是否超出一行，是的话直接溢出隐藏

					if (headName !== '') {
						column += 1;
						if (!+i) {
							theadHtmlStr += '<th class="f-center w130 minW130-imp p-top15 p-bottom15" data-column="' + (column) + '">' + headName + '</th>';//生成第一行的列
							selectHtmlStr += '<td class="f-center bg-gray p-top10 p-bottom10" data-colum="' + (column) + '" data-disable="1">' + singleSelectHtmlStr + '</td>';//生成第二行可选择的列
						}
						excelDataTrHtmlStr += '<td class="f-center bg-gray p-top10 p-bottom10' + (isOverLen ? ' no-new-line maxW130' : '') + '" data-colum="' + (column) + '" title="' + bodyValue + '">' + bodyValue + '</td>';//生成数据列
					}
				});
				if (!+i) {
					theadHtmlStr += theadEndStr;
					selectHtmlStr += '</tr>';//插入第二行可下拉行
					if (!+allColumn) allColumn = column - 1;
				}
				excelDataTrHtmlStr += '</tr>';
			}
		});
		tbodyHtmlStr += selectHtmlStr + excelDataTrHtmlStr;
		tableHtmlStr += theadHtmlStr + tbodyHtmlStr + tbodyEndStr + tableEndStr;

		$('#choseColumn').text(0);//已导入列数初始化
		$('#allColumn').text(allColumn);//更新列表所有列数量
		$(tableContentDom).html(tableHtmlStr);
	};

	return {
		clickCustomFileInput: function() {
			MYJ.verifyVipFn(true, '', function(isVip) {
				if (isVip) {
					$('#customFileInput').val('').click();
				}
			})
		},
		//将Excel解析成json数据
		getExcelData: function (files) {
			var that = this;
			WEB_EXPORT_EXCEL.excelTransformTable({
				files: files
			}, function (excelData, sourceExcelData) {
				if (sourceExcelData) that.sourceDataHandle(sourceExcelData);//重新处理数据，生成表格
			});
		},
		/* 对表格解析的源数据进行简单处理：
       *  针对表格中间空格数据用占位符代替，且只取前三行数据
       * */
		sourceDataHandle: function(sourceExcelData) {
			if (typeof sourceExcelData === 'string') sourceExcelData = JSON.parse(sourceExcelData);
			if (isEmptyObject(sourceExcelData)) {
				$.fn.message({type: 'error', msg: '导入的表格数据不能为空'});
				return;
			}

			var nextCode = '',//记住上一次的字母
				newExcelData = {},
				keyArr = getObjectKeys(sourceExcelData).sort(),//因为对象循环会导致属性乱系，所以先转成数组，然后再按照字母升序排序
				i = 0,
				maxRowNum = 0;//最大行数

			//自动填充表格内部因空白内容而缺失的单元格，用空白字符串占位代替
			var autoFillDefectRow = function (nextCode) {
				for (var n = 1; n <= 4; n++) {
					var newKey = nextCode + n;
					if (!(newExcelData.hasOwnProperty(newKey))) {
						newExcelData[newKey] = {
							h: '&nbsp;',
							r: '<t>&nbsp;</t>',
							t: 's',
							v: '&nbsp;',
							w: '&nbsp;'
						};
					}
				}
			};

			for (; i< keyArr.length; i++) {
				var key = keyArr[i],
					code = $.trim(key).replace(/[^A-Z]+/g, ''),//代表表格的列号(只取大写字母)
					num = $.trim(key).replace(/[^0-9]/ig, '');//代表表格的行号

				if (code !== '' && num !== '') {//取得表格的正常数据
					if (!(newExcelData.hasOwnProperty($.trim(key))) && num <= 4) {//取表格的前三行数据（一行表头、三行内容数据）
						newExcelData[$.trim(key)] = sourceExcelData[key];

						//  如果这次跟上一次的列号不一样，则需要循环检测前一列的数据是否都填充完，没有的则用空格占位代替
						if (nextCode && nextCode !== code) autoFillDefectRow(nextCode);
					}
					nextCode = code;//记住上一轮的列号
					if (+num > maxRowNum) maxRowNum = +num;//取最大行，判断第一列是否有空格，有的话报错拦截
				} else {//其他一些样式的字段保留
					newExcelData[$.trim(key)] = sourceExcelData[key];
				}
			}

			// 去除第一列不能为空校验
			// for (var x = 1; x <= maxRowNum; x++) {
			// 	if (!sourceExcelData.hasOwnProperty('A' + x)) {
			// 		$.fn.message({type: 'error', msg: '表格第一列不能为空'});
			// 		return false;
			// 	}
			// }

			//检测最后一列是否填充完整
			autoFillDefectRow(nextCode);
			this.showTable(XLSX.utils.sheet_to_json(newExcelData));
			nextCode = '';//释放内存
			keyArr = [];
		},
		//显示表格
		showTable: function (newExcelData) {
			creatTable(newExcelData, '#excelToTableBox');
			$('#customExcelChangeTableModal').customModal('show');
		},
		// 存为映射模板
		saveTemplate: function () {
			$('#excelTemplateName').val('');
			$('#saveExcelTemplateModal').modal('show');
		},
		submitExcelTemplate: function () {
			var name = $.trim($('#excelTemplateName').val()),
				excelTransformList = this.getExcelHeaderFields(),
				ajaxData = {
					name: name,
					order: 0,
					type: 'order'
				};
			if (!name) {
				$.fn.message({type: 'error', msg: '请输入模板名称'});
				return;
			}

			ajaxData.excelTransformList = excelTransformList;
			MYJ.ajax({
				url: 'excel/saveParamConfig.json',
				pointKey: 'saveParamConfig',
				data: JSON.stringify(ajaxData),
				contentType: 'application/json',
				success: function(res) {
					if(!+res.code) {
						$.fn.message({type: 'success', msg: '保存成功'});
						$('#saveExcelTemplateModal').modal('hide');
						EXPORT_CUSTOM_EXCEL_FN.getTemplateList(name);
					} else {
						$.fn.message({type: 'error', msg: res.msg});
					}
				}
			})
		},
		// 获取表头对应关系
		getExcelHeaderFields: function(isLow) {
			var $theadTr = $('.theadTr'),
				excelTransformList = [],
				$td = $('.selectTr td');
			$.each($td, function(i, j) {
				var $this = $(this),
					$select = $(this).find('select'),
					index = $this.attr('data-colum'),
					userKey = $theadTr.find('th[data-column="' + index + '"]').text(),
					key = $select.attr('data-key') || 'noNeedTranFlag';
				if (+i) {
					excelTransformList.push({
						key: key,
						userKey: userKey,
						index: !!isLow ? index - 1 : index
					});
				}
			})
			return excelTransformList;
		},
		// 获取模板列表
		getTemplateList: function (addName) {
			MYJ.ajax({
				url: 'excel/getParamConfigList.json',
				pointKey: 'getParamConfigList',
				data: {
					type: 'order'
				},
				success: function (res) {
					if (!+res.code) {
						var arrData = res.data || [],
                            $excelTemplateSelectId = $('#excelTemplateSelectId'),
							addId = 'none',
                            $selectEl = $excelTemplateSelectId.closest('.commSelectBox');
						$.each(arrData, function(i, j){
							var context = j.context;
							allTemplateIdsInfo[j.idStr] = JSON.parse(context);
							if(j.name === addName) {
								addId = j.idStr;
							}
						})
                        arrData.unshift({
                            id: 'none',
                            name: '无'
                        })
                        $selectEl.selectMenu({
							data: arrData,
							valueKey: 'idStr',
							position: 'fixed',
							otherDom: '<i class="iconfont icon_delete md-18 cusTooltip f-red delExcelTemBtn" title="删除" data-click="remv" onclick="EXPORT_CUSTOM_EXCEL_FN.deleteTemplaet(this)"></i>',
							// menuContentShowBox: true,
							clickCall: function (content, $iptObj, $menuListLi) {
								var $excelTemplateSelectInpur = $('#excelTemplateSelectInpur'),
									isClickDel = $excelTemplateSelectInpur.attr('data-hasDel'),
									dataValue = $menuListLi.attr('data-idStr'),
									dataName = $menuListLi.attr('data-name');
								// 点击删除触发
								$excelTemplateSelectInpur.attr('data-hasDel', false);
								if (isClickDel === 'true') {
									return;
								}
								$excelTemplateSelectId.attr('data-name', dataName).val(dataValue);
								$excelTemplateSelectInpur.val(dataName);
								EXCEL_FIELDS_FN.getCustomExcelFields(dataValue); // 重新获取分类
							}
						});
						$excelTemplateSelectId.val(addId).trigger('selectMenu:update');
						$selectEl.find('li[data-id="none"] .delExcelTemBtn').addClass('hide');
					}
				}
			})
		},
		// 切换模板
		changeExcelTemplate: function (templateId) {
			curTemplateFieldsList = templateId === 'none' ? [] : allTemplateIdsInfo[templateId]; // 当前模板列表 ( 选空 清空列表)
            // 清空映射关系
            var $td = $('.selectTr td');
            $.each($td, function(i, j) {
                var $select = $(this).find('select');
                if (+i) { // 从第二列开始
                    $select.empty().attr({
                        'data-oldvalue': '不导入',
                        'title': '不导入',
						'data-mustFlag': '',
						'data-key': 'noNeedTranFlag',
						'data-parentKdy': '',
						'data-keyIndex': '',
						'data-value': '不导入'
                    }).html('<option value="noNeedTranFlag" selected>不导入</option>');
                }
            })
            // 当前模板列表
            $.each(curTemplateFieldsList, function(i, j) { // j { key userkey index }
                var fieldKey = j.key,
                    mustFlag = '',
                    parentKey = '',
                    curKeyIndex = i,
					defaultKeyInfo = {key: 'noNeedTranFlag', value: '不导入', mustFlag: false, innerList: null},
                    curKeyInfo = excelFielsKeysInfo[fieldKey] || defaultKeyInfo,
                    $curSelect= $('.selectTr').find('td[data-colum="' + j.index + '"] select'),
                    curValue = curKeyInfo.value,
                    optionStr = '<option value="' + fieldKey +'" selected>' + curValue + '</option>';
                // 去除一级字段列表
                for (var di = excelHeaderFields.length -1; di > -1 ; di--) {
                    if (j.key === excelHeaderFields[di].key && j.key !== 'noNeedTranFlag') {
                        excelHeaderFields.splice(di, 1);
                        mustFlag = excelHeaderFields[di].mustFlag;
                    }
                }
                // 去除二级字段列表
                $.each(getObjectKeys(excelHFieldsInnerList), function(ki, parentKeyname){
                    for (var di = excelHFieldsInnerList[parentKeyname].length -1; di > -1 ; di--) {
                        if (j.key === excelHFieldsInnerList[parentKeyname][di].key) {
                            parentKey = parentKeyname;
                            mustFlag = excelHFieldsInnerList[parentKeyname][di].mustFlag;
                            excelHFieldsInnerList[parentKey].splice(di, 1);
                        }
                    }
                })
                // 将选项赋值到对应的列
                $curSelect.empty().attr({
					'data-oldvalue': curValue,
					'title': curValue,
                    'data-mustFlag': mustFlag,
                    'data-key': fieldKey,
                    'data-parentKdy': parentKey,
                    'data-keyIndex': curKeyIndex,
                    'data-value': curValue
                }).html(optionStr);
            });

			EXCEL_FIELDS_FN.totalColunNum(); // 统计选中字段数量
		},
		// 删除模板
		deleteTemplaet: function (obj) {
			var $excelTemplateSelectId = $('#excelTemplateSelectId'),
				$li = $(obj).closest('li'),
				curName = $li.attr('data-name'),
				curId = $li.attr('data-idStr');
			$('#excelTemplateSelectInpur').attr('data-hasDel', true).val($excelTemplateSelectId.attr('data-name'));
			if (curId === $excelTemplateSelectId.val()) {
				$.fn.message({type: 'error', msg: '当前已选择模板不可删除'});
				return;
			}
			MYJ.confirm({
				type: 'delete',
				isText: true,
				title: '确定删除？',
				content: '将删除"' + curName + '"，确定要继续操作吗？',
				callback: function (v) {
					if (v) {
						MYJ.ajax({
							url: 'excel/delParamConfig.json',
							pointKey: 'delParamConfig',
							data: {
								id: curId
							},
							success: function(res) {
								if(!+res.code) {
									$.fn.message({type: 'success', msg: '删除成功'});
									EXPORT_CUSTOM_EXCEL_FN.getTemplateList();
								} else {
									$.fn.message({type: 'error', msg: res.msg});
								}
							}
						})
					}
				}
			});
		},

		// 导入模板
		uploadOtherFile: function () {
			var isNotVip = false;
			MYJ.verifyVipFn(true, '', function(isVip) {
				if (isVip) {
					isNotVip = !isVip;
				}
			})
			if(isNotVip) return;
			var formData = new FormData(),
				excelTransformConfig = {
					name: $('#excelTemplateSelectId').attr('data-name') || '无',
					order: '0',
					type: 'order',
				};

			excelTransformConfig.excelTransformList = this.getExcelHeaderFields(true);
			formData.append('FileData', $('#customFileInput')[0].files[0]);
			formData.append('excelTransformConfig', JSON.stringify(excelTransformConfig));
			commonProgressBarModalShow({
				title: '导入自定义文件',
				statusText: '导入中...',
				successText: '导入成功！',
				unit: '条',
				isDownLoad: false,
				multiFileSize: 10000, // 每个文件的数据条数
				ajaxUrl: 'excel/userImport.json',
				ajaxData: formData,
				cache: false,//上传文件无需缓存
				processData: false,//用于对data参数进行序列化处理 这里必须false
				contentType: false, //必须
				callback: function () { // 进度条弹层执行完
				},
				closeCallback: function () { // 进度条弹层关闭时
				}
			})
		}
	}
})(jQuery, document, window);